美文网首页
创建型-抽象工厂

创建型-抽象工厂

作者: iarchitect | 来源:发表于2019-03-31 16:34 被阅读0次

    抽象工厂模式:

    抽象工厂模式是工厂方法的升级版,用来创建一组相关或互相依赖的对象。
    举个例子:高配汽车使用A类引擎和A类空调,低配汽车使用B类引擎和B类空调,此时需要两类工厂进行生产

    public interface AirCondition {
    }
    
    public class AirConditionA implements AirCondition {
        public AirConditionA(){
            System.out.println("制造-->空调A");
        }
    
    }
    
    public class AirConditionB implements AirCondition {
    
        public AirConditionB(){
            System.out.println("制造-->空调B");
        }
    }
    
    
    public interface Engine {
    }
    public class EngineA implements Engine {
        public EngineA(){
            System.out.println("制造-->引擎A");
        }
    }
    public class EngineB implements Engine{
        public EngineB(){
            System.out.println("制造-->引擎B");
        }
    }
    
    
    public interface IFactory {
        //制造发动机
        public Engine createEngine();
        //制造空调
        public AirCondition createAirCondition();
    }
    
    public class FactoryA implements IFactory {
    
        @Override
        public Engine createEngine() {
            return new EngineA();
        }
    
        @Override
        public AirCondition createAirCondition() {
            return new AirConditionA();
        }
    }
    
    public class FactoryB implements IFactory{
    
        @Override
        public Engine createEngine() {
            return new EngineB();
        }
    
        @Override
        public AirCondition createAirCondition() {
            return new AirConditionB();
        }
    }
    
    
    public class Client {
        public static void main(String[] args) {
            FactoryA factoryA = new FactoryA();
            factoryA.createEngine();
            factoryA.createAirCondition();
    
            FactoryB factoryB = new FactoryB();
            factoryB.createEngine();
            factoryB.createAirCondition();
        }
    }
    
    

    运行结果

    image.png

    相关文章

      网友评论

          本文标题:创建型-抽象工厂

          本文链接:https://www.haomeiwen.com/subject/zilubqtx.html