工厂模式

工厂模式

简单工厂(静态工厂)

虽然某种程度上不符合设计原则,但实际使用最多

Car

public interface Car {
    void name();
}

Wuling

public class Wuling implements Car{
    @Override
    public void name() {
        System.out.println("五菱");
    }
}

Tesla

public class Tesla implements Car{
    @Override
    public void name() {
        System.out.println("特斯拉");
    }
}

Factory

/*
* 简单工厂(静态工厂)
* 增加一个新的产品,就必须修改原来代码
* 开闭原则
* 角色:产品接口,具体产品类,工厂类,
* 使用时:通过工厂类,传入不同参数,获取不同产品
*       或者调用工厂类针对不同产品的方法
* */
public class Factory {

    //方法1
    public static Car getCar(String car) {
        if ("五菱".equals(car)) {
            return new Wuling();
        } else if ("特斯拉".equals(car)) {
            return new Tesla();
        } else {
            return null;
        }
    }

    //方法2
    public static Car getWuling(){
        return new Wuling();
    }
    public static Car getTesla(){
        return new Tesla();
    }
}

Consumer

public class Consumer {
    public static void main(String[] args) {

        //方法1
        Car car1 = Factory.getCar("五菱");
        Car car2 = Factory.getCar("特斯拉");
        car1.name();
        car2.name();

        //方法2
        Car car3 = Factory.getWuling();
        Car car4 = Factory.getTesla();
        car3.name();
        car4.name();

    }
}
工厂方法

Car

public interface Car {
    void name();
}

Wuling

public class Wuling implements Car{
    @Override
    public void name() {
        System.out.println("五菱");
    }
}

Tesla

public class Tesla implements Car{
    @Override
    public void name() {
        System.out.println("特斯拉");
    }
}

Factory

/*
* 工厂方法模式
* 角色:产品接口,具体产品类,工厂接口,每种产品的工厂类
* 使用:new 不同产品的工厂类,调用他们的方法
* */
public interface Factory {
    Car getCar();
}

WulingFactory

public class WulingFactory implements Factory {
    @Override
    public Car getCar() {
        return new Wuling();
    }
}

TeslaFactory

public class TeslaFactory implements Factory {
    @Override
    public Car getCar() {
        return new Tesla();
    }
}

Consumer

public class Consumer {
    public static void main(String[] args) {
        Car car1 = new WulingFactory().getCar();
        Car car2 = new TeslaFactory().getCar();
        car1.name();
        car2.name();
    }
}
posted @ 2021-12-13 15:34  jpy  阅读(13)  评论(0)    收藏  举报