简体   繁体   English

创建对象的设计模式

[英]Design pattern for object creation

have to create an abstract class, say Part. 零件说,必须创建一个抽象类。 But there are two type of parts, 但是有两种类型的零件,

Part1: This part has 3 instance variables, inside,outside,middle 第一部分:这部分具有3个实例变量,内部,外部,中间

Part2: This part has 2 instance variables, top, bottom 第2部分:这部分有2个实例变量,分别是top,bottom

Finally, both Part are extending an abstract class Part, so finally, in Java its like this 最后,两个Part都扩展了一个抽象类Part,所以最后,在Java中,它像这样

abstract Class Object{
   public abstract String toString();
}

abstract class Part{
    abstract void print();
}

Class Part1 extends Part1{
    List <Object> inside = new ArrayList <Object> ();
    List <Object> outside = new ArrayList <Object> ();
    List <Object> medium = new ArrayList <Object> ();
    void print(){
        //go through all the list and print the object
    }
}

Class Part1 extends Part2{
    List <Object> top = new ArrayList <object> ();
    List <Object> bottom = new ArrayList <object> ();
    void print(){
        //go through all the list and print the object
    }
}

my issue is which design pattern can I apply for the creation of Part, I'm still a newbie in pattern, for me its builder because I have to come up with the same type of Object having different representation. 我的问题是我可以申请哪种设计模式来创建零件,我仍然是模式的新手,对我来说,它的生成器是因为我必须提出具有不同表示形式的同一类型的对象。 But the object is not complex !! 但是对象并不复杂!

See http://en.wikibooks.org/wiki/C%2B%2B_Programming/Code/Design_Patterns#Creational_Patterns . 请参阅http://en.wikibooks.org/wiki/C%2B%2B_Programming/Code/Design_Patterns#Creational_Patterns

I prefere factory pattern usage or prototype: 我更喜欢使用工厂模式或使用原型:

Prototype example: 原型示例:

Class PartsFactory
{
    Part createPart(string partType)
    {
        if (partType.equals("Type1")) return new Part1();
        if (partType.equals("Type2")) return new Part2();
        return null;
    }
}

Factory example: 工厂示例:

interface PartsFactory
{
    Part createPart();
}

Class Parts1Factory implements PartsFactory
{
    Part createPart()
    {
        return new Part1();
    }
}

Class Parts2Factory implements PartsFactory
{
    Part createPart()
    {
        return new Part2();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM