Factory Pattern

本文探讨了两种工厂模式:简单工厂模式和通用工厂模式。简单工厂模式易于实现,但不遵循开闭原则,当增加新类型时需修改工厂类。而通用工厂模式遵循开闭原则,通过创建特定对象的工厂类来适应变化,但可能导致更多的类和代码。
摘要由CSDN通过智能技术生成

Factory pattern has 2 types, simple factory and general factory patterns.

Simple factory pattern:

Factory class helps create new objects, whenever needs to create a new object, ask factory class to return.

Advantages: Simple, easy to apply, only factory class needs adjustments when new type of objects is involved. Widely used.

Disadvantage: Doesn't meet open and close principle, when extends new types of objects, need to update factory class.

UML class diagram:

 

Pizza pizza = PizzaSimpleFactory.createPizza(pizzaType);

General factory pattern:

Each type of object will have own combination of object class and factory class, when new object is required, will create the new object and new object's factory classes.

Advantages: Meet open and close principle

Disadvantages: Too many classes and code

UML class diagram:

 

 

String pizzaType = pizzaTypeStream.readLine();
Pizza pizza = null;
if (location.equals("Bei Jing")) {
    pizza = new BJPizzaFactory().createPizza(pizzaType);
} else if (location.equals("Tian Jin")) {
    pizza = new TJPizzaFactory().createPizza(pizzaType);
} else {
    System.out.println("The location you choose is not supported");
    return;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值