设计模式-创建型-抽象工厂

1、定义

抽象工厂:创建相关依赖对象家族,而无须指定具体类

代码

抽象工厂

/**
 * 制动
 */
public interface IBrake {
    void brake();
}

/**
 * 发动机
 */
public interface IEngine {
    void engine();
}

//轮胎
public interface ITire {
    void tire();
}

/**
 * 汽车工厂
 */
public interface ICarFactory {

    IBrake createBrake();
    IEngine createEngine();
    ITire createTire();

}

具体实现

public class NormalBrake implements IBrake {

    @Override
    public void brake() {

    }

}

public class NormalEngine implements IEngine {

    @Override
    public void engine() {

    }
}

public class NormalTire implements ITire {
    @Override
    public void tire() {

    }
}

public class NormalFactory implements ICarFactory {
    @Override
    public IBrake createBrake() {
        return new NormalBrake();
    }

    @Override
    public IEngine createEngine() {
        return new NormalEngine();
    }

    @Override
    public ITire createTire() {
        return new NormalTire();
    }
}

客户端调用

/**
 * 一簇抽象接口
 */
public class TestMain {

    public static void main(String[] args) {
        ICarFactory normalFactory = new NormalFactory();
        normalFactory.createBrake().brake();
        normalFactory.createEngine().engine();
        normalFactory.createTire().tire();
    }

}

代码示例

https://github.com/yinlingchaoliu/23-design-pattern

你可能感兴趣的:(设计模式-创建型-抽象工厂)