开发者

How to set different properties from objects which are returned by the Factory pattern?

I was wondering on how to set properties on which objects which are returned by the concrete factory. The factory can return objectA with properties A and B, but it can also return objectB with properties X开发者_如何学运维, Y, Z.

Since the client only know the interface objectA and objectB inherits, it doesn't know which object he is dealing with. So, my question is, what is the OO way of setting these properties? Do I need to introduce a kind of setting class, which contains all the properties of classA and classB? But this isn't OO, because when there's a new class I have to update the setting class as well...

I hope you undserstand my question and can help me out :)

PS: If it matters, I am working with C#


You can use a visitor which knows which properties to set and can assign it to the concrete class which you get (inside the factory). Now this visitor can set the desired properties in abstract way.

class Factory {

..
obj = new ConcreteObject();
obj.accept(new ConcreteObjectVisitor());
}

class ConcreteObject{

accept(Visitor visitor){
 visitor.visit(this);
}

}

class ConcreteObjectVisitor implements Visitor {

visit(ConcretTypeInterface param){

obj = (ConcretType)param;
param.setA()
param.setB()
param.setC()
}
}


If client needs to set values of properties that don't exist in common interface, it has to have some knowledge on concrete types of objects that the factory has created. There are several approaches to this:

  1. Client decides what kind of object it needs and calls appropriate factory operation. So for this scenario, the factory would have a different operations for creating objectA and objectB. Values of properties to be set could be passed as parameters of those operations.

  2. Client decides what kind of object it needs and passes this decision to factory as a value of a parameter of factory method. The values themselves are passed as a single array, collection or dictionary object in another parameter.

  3. Factory decides what class to instantiate, passes new instance to client and then client discovers the concrete class of given object (in C# via GetType() method). If concrete class is accessible to client, it can perform a cast, if not, it can set values of properties using reflection.

If examples are needed, just write a comment :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜