抽象工厂设计模式
抽象工厂是应对产品族概念的。比如说,每个汽车公司可能要同时生产轿车,货车,客车,那么每一个工厂都要有创建轿车,货车和客车的方法。
应对产品族概念而生,增加新的产品线很容易,但是无法增加新的产品。
抽象工厂:用来生产不同产品族的全部产品。(对于增加新的产品,无能为力;支持增加产品族)
代码 demo01
package three;
public interface Sample {
public void method();
}
package three;
public class SampleA implements Sample {
@Override
public void method() {
// TODO Auto-generated method stub
System.out.println("SampleA................");
}
}
package three;
public class SampleB implements Sample {
@Override
public void method() {
// TODO Auto-generated method stub
System.out.println("SampleB..........................");
}
}
package three;
public interface Bomb {
public void method();
}
package three;
public class BombA implements Bomb {
@Override
public void method() {
// TODO Auto-generated method stub
System.out.println("BombA.................");
}
}
package three;
public class BombB implements Bomb {
@Override
public void method() {
// TODO Auto-generated method stub
System.out.println("BombB..................");
}
}
package three;
/**
* 抽象工厂的实现
*
* @author Administrator
*
*/
public class BombFactory extends Factory {
public Sample creator() {
return new SampleB();
}
public Bomb creator(String className) {
BombB bombB = null;
try {
if (bombB == null) {
bombB = (BombB) Class.forName(className).newInstance();
}
} catch (Exception e) {
e.printStackTrace();
}
return bombB;
}
}
package three;
import one.Product;
/**
* 抽象工厂的实现
* @author Administrator
*
*/
public class SimpleFactory extends Factory {
public Sample creator() {
return new SampleA();
}
public Bomb creator(String className) {
BombA bombA = null ;
try{
bombA = (BombA)Class.forName(className).newInstance() ;
}catch(Exception e){
e.printStackTrace() ;
}
return bombA;
}
}
测试方法 :
package three;
public class TestBombFactory {
public static void main(String[] args) {
BombB bombB = (BombB) new BombFactory().creator("three.BombB");
bombB.method();
SampleB sampleB = (SampleB) new BombFactory().creator();
sampleB.method();
}
}
package three;
public class TestSampleFactory {
public static void main(String[] args) {
BombA bombBA = (BombA) new SimpleFactory().creator("three.BombA");
bombBA.method();
SampleA sampleA = (SampleA) new SimpleFactory().creator();
sampleA.method();
}
}