阅读网站源码,专门做外贸网站有哪些,怎么组建企业网站,湖州医院网站建设方案工厂模式#xff08;Factory Pattern#xff09;是一种常用的设计模式#xff0c;它提供了一种封装创建对象过程的方法。通过工厂方法或工厂类#xff0c;你可以将对象的创建与使用分离#xff0c;使得代码更加灵活和可维护。工厂模式主要分为三种类型#xff1a;简单工厂…工厂模式Factory Pattern是一种常用的设计模式它提供了一种封装创建对象过程的方法。通过工厂方法或工厂类你可以将对象的创建与使用分离使得代码更加灵活和可维护。工厂模式主要分为三种类型简单工厂模式Simple Factory Pattern、工厂方法模式Factory Method Pattern和抽象工厂模式Abstract Factory Pattern。
1. 简单工厂模式Simple Factory Pattern
简单工厂模式也称为静态工厂方法模式它不属于GOF四人帮的23种设计模式之一但在实际应用中非常常见。它由一个工厂类根据传入的参数决定创建哪一种产品类的实例。
优点
客户端不需要直接实例化对象降低了耦合度。提高了代码的复用性和可维护性。
缺点
工厂类集中了所有产品创建逻辑违反了高内聚原则。当添加新产品时需要修改工厂类的代码违反了开闭原则。
示例代码Java
// 产品接口
public interface Product {void use();
}// 具体产品A
public class ProductA implements Product {Overridepublic void use() {System.out.println(使用产品A);}
}// 具体产品B
public class ProductB implements Product {Overridepublic void use() {System.out.println(使用产品B);}
}// 工厂类
public class SimpleFactory {public static Product createProduct(String type) {if (A.equals(type)) {return new ProductA();} else if (B.equals(type)) {return new ProductB();} else {return null;}}
}// 客户端代码
public class Client {public static void main(String[] args) {Product productA SimpleFactory.createProduct(A);productA.use();Product productB SimpleFactory.createProduct(B);productB.use();}
}2. 工厂方法模式Factory Method Pattern
工厂方法模式定义一个用于创建对象的接口让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
优点
客户端不需要知道它所使用的对象的类。一个类仅负责一种产品或一个产品族系的创建。将对象的创建与使用解耦。
缺点
系统中类的个数将成对增加在一定程度上增加了系统的复杂性。
示例代码Java
// 抽象产品接口
public interface Product {void use();
}// 具体产品A
public class ProductA implements Product {Overridepublic void use() {System.out.println(使用产品A);}
}// 具体产品B
public class ProductB implements Product {Overridepublic void use() {System.out.println(使用产品B);}
}// 抽象工厂接口
public interface Creator {Product createProduct();
}// 具体工厂A
public class CreatorA implements Creator {Overridepublic Product createProduct() {return new ProductA();}
}// 具体工厂B
public class CreatorB implements Creator {Overridepublic Product createProduct() {return new ProductB();}
}// 客户端代码
public class Client {public static void main(String[] args) {Creator creatorA new CreatorA();Product productA creatorA.createProduct();productA.use();Creator creatorB new CreatorB();Product productB creatorB.createProduct();productB.use();}
}3. 抽象工厂模式Abstract Factory Pattern
抽象工厂模式提供一个接口用于创建相关或依赖对象的家族而不需要明确指定具体类。
优点
可以在不知道具体类名的情况下创建一系列相互关联或相互依赖的产品对象。增加了系统的灵活性和可扩展性。
缺点
产品族扩展困难假设要增加一个新的产品C那么就需要修改所有的工厂类添加相应的方法。系统复杂性提高由于使用到了多个工厂等级结构使得系统的抽象性和复杂性提高。
示例代码Java
由于抽象工厂模式较为复杂暂不提供