Skip to content

工厂模式

定义一个创建对象的接口,让子类决定实例化哪个类

简单工厂模式

又称静态工厂方法模式

根据参数不同返回不同类实例

定义一个类负责创建其他类实例,被创建的类通常拥有共同的父类

优点:创建和使用分离

缺点:不够灵活,新增一个产品类就要修改工厂的判断逻辑

java
package factory.simple;

public abstract class Product {
    public abstract void print();
}
java
package factory.simple;

public class ProductA extends Product {
    @Override
    public void print() {
        System.out.println("SimpleFactory A");
    }
}
java
package factory.simple;

public class ProductB extends Product {
    @Override
    public void print() {
        System.out.println("SimpleFactory B");
    }
}
java
package factory.simple;

public class SimpleFactory {
    public static Product createProduct(String type) {
        if ("A".equals(type)) {
            return new ProductA();
        }
        if ("B".equals(type)) {
            return new ProductB();
        }
        return null;
    }
}

抽象工厂模式

java
package factory.abs;

public interface Phone {
    void print();
}
java
package factory.abs;

public class Huawei implements Phone {
    @Override
    public void print() {
        System.out.println("Huawei");
    }
}
java
package factory.abs;

public class Apple implements Phone {
    @Override
    public void print() {
        System.out.println("Apple");
    }
}
java
package factory.abs;

public interface Factory {
    Phone createPhone();
}
java
package factory.abs;

public class HuaweiFactory implements Factory {
    @Override
    public Phone createPhone() {
        return new Huawei();
    }
}
java
package factory.abs;

public class AppleFactory implements Factory {
    @Override
    public Phone createPhone() {
        return new Apple();
    }
}

最近更新:

All articles are under CC BY 4.0 license