抽象工厂模式概念
抽象工厂还有另外一个关键要点,是因为 SimpleFactory内,生产Sample和生产Sample2的方法之间有一定联系,所以才要将这两个方法捆绑在一个类中,这个工厂类有其本身特征,也许制造过程是统一的,比如:制造工艺比较简单,所以名称叫SimpleFactory。在实际应用中,工厂方法用得比较多一些,而且是和动态类装入器组合在一起应用,
抽象工厂模式结构图
抽象工厂模式实现步骤
第一步:创建Car接口以及它的实现类BMW和Benzi
/**
* Created by Walter on 2017/3/15.
*/
public interface Car {
void run();
}
/**
* Created by Walter on 2017/3/15.
*/
public class BMW implements Car {
@Override
public void run() {
System.out.println("BMW RUN");
}
}
/**
* Created by Walter on 2017/3/15.
*/
public class Benzi implements Car {
@Override
public void run() {
System.out.println("Benzi RUN");
}
}
第二步:创建Color接口以及它的实现类WhiteColor和BlueColor
/**
* Created by Walter on 2017/3/15.
*/
public interface Color {
void draw();
}
/**
* Created by Walter on 2017/3/15.
*/
public class White implements Color{
@Override
public void draw() {
System.out.println("WHITE COLOR");
}
}
/**
* Created by Walter on 2017/3/15.
*/
public class Blue implements Color{
@Override
public void draw() {
System.out.println("BLUE COLOR");
}
}
第三步:创建抽象工厂AbstractFactory
/**
* Created by Walter on 2017/3/15.
*/
public abstract class AbstractFactory {
abstract Car getCar(int carType);
abstract Color getColor(int colorType);
}
/**
* Created by Walter on 2017/3/15.
*/
public class CarFactory extends AbstractFactory{
public static int BMW = 1;
public static int BENZI = 2;
@Override
public Car getCar(int type){
switch (type){
case 1:
return new BMW();
case 2:
return new Benzi();
}
return null;
}
@Override
Color getColor(int colorType) {
return null;
}
}
public class ColorFactory extends AbstractFactory{
public static int WHITE = 1;
public static int BLUE = 2;
@Override
Car getCar(int carType) {
return null;
}
@Override
Color getColor(int colorType) {
switch (colorType){
case 1:
return new White();
case 2:
return new Blue();
}
return null;
}
}
第四步:创建工厂生产者
/**
* Created by Walter on 2017/3/15.
*/
public class FactoryProducer {
public static int COLOR_FACTORY = 1;
public static int CAR_FACTORY = 2;
AbstractFactory getFactory(int factoryType) {
switch (factoryType){
case 1:
return new ColorFactory();
case 2:
return new CarFactory();
}
return null;
}
}
第五步:创建测试类
/**
* Created by Walter on 2017/3/15.
*/
public class TestMain {
public static void main(String[] args){
//1、创建工厂生产者
FactoryProducer producer = new FactoryProducer();
//2、根据类型创建对应的工厂
CarFactory carFac = (CarFactory) producer.getFactory(FactoryProducer.CAR_FACTORY);
//3、根据类型通过工厂创建对应产品
BMW bmw = (BMW) carFac.getCar(CarFactory.BMW);
//4、产品展示操作
bmw.run();
}
}
测试结果