开发者

Factory class with given specs

I've the following requirement for one of the applications that I'm working on in Java.

Have a factory class C, having the following method create(int src), that creates objects of classes A and B.

The method creates object of clas开发者_如何学编程s A, if src=1; object of class B,if src=2. Ensure no other class other than C can create objects of A and B.

I cannot use reflection.

This is what I tried till now.

class C{

 private int src;

 public c(){
  …//Default constructor
}

public create (int src){

 if(src = 1){
  A aobj = new A();
}
else if (src=2){
 B bobj = new B();
} 

} 

} 

How can I improve the class defination to make sure its more consistent with original specs?

Thanks.


The right way to define a factory class (I suppose you have the Abstract factory patten in mind) is by implementing an interface:

public interface IAbstract { }
public class A implements IAbstract { }
public class C implements IAbstract { }

// The factory interface that creates concrete implementations of IAbstract.
public interface IAbstractFactory {
    public IAbstract create();
}

public class AFactory implements IAbstractFactory {
    public IAbstract create() {
        return new A();
    }
} 

public class BFactory implements IAbstractFactory {
    public IAbstract create() {
        return new B();
    }
} 

The factory implementation to use is chosen based on some application configuration. That means, the condition you have in your factory class will move to a higher-level in code:

public static void main(String args[]) {
    int src = Integer.parseInt(args[0]);
    IAbstractFactory factory = null;
    if (src == 1)
        factory = new AFactory();
    else if (src == 2)
        factory = new BFactory();
    IAbstract obj = factory.create();
    // ....
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜