工厂方法设计模式
工厂方法是针对每一种产品提供一个工厂类。通过不同的工厂实例来创建不同的产品实例。
在同一等级结构中,支持增加任意产品。
工厂方法 :用来生产同一等级结构中的固定产品。(支持增加任意产品)
代码
demo 01
package two.frist;
public interface Sample {
public void method();
}
package two.frist;
public class SampleA implements Sample {
@Override
public void method() {
// TODO Auto-generated method stub
System.out.println("SampleAaaaaa");
}
}
package two.frist;
public class SampleB implements Sample {
@Override
public void method() {
// TODO Auto-generated method stub
System.out.println("SampleBbbbbbb");
}
}
package two.frist;
public class SampleC implements Sample {
@Override
public void method() {
// TODO Auto-generated method stub
System.out.println("SampleCcccccccccccc");
}
}
package two.frist;
/**
* 工厂方法
*
* @author xxg
*
*/
public class Factory {
public static Sample creator(int which) {
Sample sample = null;
// getClass 产生Sample 一般可使用动态类装载装入类。
if (which == 1) {
sample = new SampleA();
} else if (which == 2) {
sample = new SampleB();
} else if (which == 3) {
sample = new SampleC();
}
return sample;
}
}
package two.frist;
public class Test {
/**
* 工厂方法测试
*
* @param args
*/
public static void main(String[] args) {
Sample sampleA = Factory.creator(1);
sampleA.method();
Sample sampleB = Factory.creator(2);
sampleB.method();
Sample sampleC = Factory.creator(3);
sampleC.method();
}
}