Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【设计模式-创建型】工厂方法模式 #68

Open
SilenceHVK opened this issue Jul 24, 2019 · 0 comments
Open

【设计模式-创建型】工厂方法模式 #68

SilenceHVK opened this issue Jul 24, 2019 · 0 comments

Comments

@SilenceHVK
Copy link
Owner

定义: 定义一个创建对象的接口,让子类决定实例哪一个类。工厂方法使一个类的实例化延迟到其子类

类型:创建型

适用场景:

  • 创建对象需要大量重复的代码;
  • 客户端不依赖于产品类实例如何被创建、实现等细节;
  • 一个类通过其子类来指定创建哪个对象;

优点:

1. 用户只需关心所需产品对应的工厂,无须关心创建细节;
2. 加入新产品符合开闭原则,提高可扩展性;

缺点:

1. 类的个数过容易过多,增加复杂度;
2. 增加系统的抽象性和理解难度;

UML 图:

Factory Method

示例代码:

  • Abstract Product
public abstract class Product {
    
}
  • Concrete ProductA
public class ProductA extends Product {
    
}
  • Concrete ProductB
public class ProductB extends Product {
    
}
  • Product Factory
public abstract class ProductFactory {

    public abstract Product getProduct();
}
  • Concrete ProductA Factory
public class ProductAFactory extends ProductFactory {

     public Product getProduct() {
         return new ProductA();
     }
}
  • Concrete ProductB Factory
public class ProductBFactory extends ProductFactory {

     public Product getProduct() {
         return new ProductB();
     }
}
  • Client
public class Client {
    public static void main(String [] args){
    
        ProductFactory productAFactory = new ProductAFactory();
        Product productA = productAFactory.getProduct();
        
        ProductFactory productBFactory = new ProductBFactory();
        Product productB = productBFactory.getProduct();
        
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant