工厂方法

来源:互联网 发布:软件著作权申报 编辑:程序博客网 时间:2024/06/05 04:38

要得到一个对象,不用new ,而是通过工厂方法得到目标对象的实例

public class ISample {
}

public class SampleA extends ISample{
}

public class SampleB extends ISample{
}

public class Factory {
    public static ISample create(int i){
        switch (i) {
        case 1:
            return new SampleA();
        case 2:
            return new SampleB();
        default:
            break;
        }
        return null;
    }
}
public class Test {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ISample sample = Factory.create(1);
    }
}



0 0