二十三种设计模式之抽象工厂模式
抽象工厂模式
用于生产不同产品族的全部产品(对于增加新的产品,无能为力,支持增加产品族)
抽象工厂模式是对同种业务,不同情况
应用场景
- JDK 中 Calendar 的 getInstance() 方法
- JDBC 中 Connection 对象的获取
- Spring 中 IOC 容器创建管理 Bean 对象
- XML 解析时的 DocumentBuiulderFactory 创建解析器对象
- 反射中 Class 对象的 newInstance()
优势劣势
Engine 接口及其实现类
package factory.abstra; /** * @author SIMBA1949 * @date 2019/6/6 11:21 */ public interface Engine { void speedRatio(); } class LowEngine implements Engine{ public void speedRatio() { System.out.println("低端引擎,转速慢"); } } class LuxuryEngine implements Engine{ public void speedRatio() { System.out.println("高端引擎,转速快"); } }
Seat 接口及其实现类
package factory.abstra; /** * @author SIMBA1949 * @date 2019/6/6 11:22 */ public interface Seat { void function(); } class LowSeat implements Seat{ public void function() { System.out.println("低端座椅"); } } class LuxurySeat implements Seat{ public void function() { System.out.println("高端座椅"); } }
Tire 接口及其实现类
package factory.abstra; /** * @author SIMBA1949 * @date 2019/6/6 11:22 */ public interface Tire { void durability(); } class LowTire implements Tire{ public void durability() { System.out.println("低端轮胎"); } } class LuxuryTire implements Tire{ public void durability() { System.out.println("高端轮胎"); } }
抽象工厂 及其实现类
package factory.abstra; /** * @author SIMBA1949 * @date 2019/6/6 11:26 */ public interface ProductsFactory { Engine createEngine(); Seat createSeat(); Tire createTire(); } class LowProductFactory implements ProductsFactory { public Engine createEngine() { return new LowEngine(); } public Seat createSeat() { return new LowSeat(); } public Tire createTire() { return new LowTire(); } } class LuxuryProductFactory implements ProductsFactory { public Engine createEngine() { return new LuxuryEngine(); } public Seat createSeat() { return new LuxurySeat(); } public Tire createTire() { return new LuxuryTire(); } }
Client 测试
package factory.abstra; /** * @author SIMBA1949 * @date 2019/6/6 11:29 */ public class AbstractFactoryClient { public static void main(String[] args) { Engine lowEngine = new LowProductFactory().createEngine(); Seat lowSeat = new LowProductFactory().createSeat(); Tire lowTire = new LowProductFactory().createTire(); Engine luxuryEnginer = new LuxuryProductFactory().createEngine(); Seat luxurySeat = new LuxuryProductFactory().createSeat(); Tire luxuryTire = new LuxuryProductFactory().createTire(); } }