需要增加UML
需要增加UML
需要增加UML

开发中通常使用new产生一个对象的实例

无模式

//生产Audi
public class Audi{
    public Audi(){
        System.out.println("制造 audi.....");
    }
}
//生产Benz
public class Benz {
    public Benz(){
        System.out.println("制造Benz....");
    }
}
//客户使用new生产一辆车
public class Customer{
    public static void main(String[] args) {
        Audi audi = new Audi();
        Benz benz = new Benz();
    }
}

简单工厂(SimpleFactory)模式

abstract class Car {
    public Car() {
    }
}
public class Audi extends Car {
    public Audi(){
        System.out.println("制造 audi.....");
    }
}
public class Benz extends  Car {
    public Benz(){
        System.out.println("制造Benz....");
    }
}

传入不同的参数生产不同的车

public class Factory {
    public Car createCar(String type) {
        switch (type) {
            case "audi":
                return new Audi();
            case "benz":
                return new Benz();
            default:
                break;
        }
        return null;
    }
}

原来客户自己生产车改为由车工厂生产车

public class Customer {
    public static void main(String[] args) {
        Factory factory = new Factory();
        Car audi = factory.createCar("audi");
        Car benz = factory.createCar("benz");
    }
}

工厂方法(FactoryMethod)模式

车抽象类Car

abstract class Car {

    public Car() {

    }
}
public class Audi extends Car {

    public Audi(){
        System.out.println("创建Audi...");
    }
}
public class Benz extends Car {
    public Benz() {
        System.out.println("创建benz....");
    }
}

生产车的工厂接口

public interface CarFactory {
    Car createCar();
}
public class AudiFactory implements CarFactory {

    @Override
    public Audi createCar() {
        return new Audi();
    }
}
public class BenzFactory implements CarFactory {

    @Override
    public Benz createCar() {
        return new Benz();
    }
}
public class Customer {

    public static void main(String[] args) {
        AudiFactory audiFactory = new AudiFactory();
        Audi audi = audiFactory.createCar();

        BenzFactory benzFactory = new BenzFactory();
        Benz benz = benzFactory.createCar();
    }
}

标签: 设计模式, 工厂模式

添加新评论