设计模式之工厂模式
设计模式 Java About 1,689 words简单工厂
由一个工厂对象决定创建出具体哪个类。
public class SimpleFactory {
public Pizza createPizza(String type) {
Pizza pizza = null;
switch (type) {
case "cheese":
pizza = new CheesePizza();
break;
case "pepper":
pizza = new PepperPizza();
break;
default:
break;
}
return pizza;
}
}
工厂方法
定义一个用于创建对象的抽象方法,由子类决定实例化具体的类,将对象的实例化推迟到子类。
public abstract class FactoryMethod {
public abstract Pizza createPizza(String type);
public static void main(String[] args) {
String pizzaType = "cheese";
Pizza pizza = null;
if (pizzaType.equals("cheese")) {
pizza = new CheeseFactoryMethod().createPizza(pizzaType);
} else if (pizzaType.equals("pepper")) {
pizza = new PepperFactoryMethod().createPizza(pizzaType);
}
System.out.println(pizza.toString());
}
}
抽象工厂
- 将简单工厂模式和工厂方法模式进行整合
- 将工厂抽象成两层,抽象工厂和具体实现的工厂子类
- 根据创建对象类型使用对应的工厂子类
- 将单个的简单工厂类变成了工厂簇
public interface AbstractFactory {
Pizza createPizza();
static void main(String[] args) {
PizzaFactory pizzaFactory = new PizzaFactory();
pizzaFactory.create(new CheesePizzaFactory());
Pizza pizza = pizzaFactory.abstractFactory.createPizza();
System.out.println(pizza.toString());
}
}
public class CheesePizzaFactory implements AbstractFactory{
@Override
public Pizza createPizza() {
return new CheesePizza();
}
}
public class PepperPizzaFactory implements AbstractFactory {
@Override
public Pizza createPizza() {
return new PepperPizza();
}
}
Views: 2,342 · Posted: 2019-12-13
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...