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

【设计模式-创建型】简单工厂模式 #67

Open
SilenceHVK opened this issue Jun 16, 2019 · 0 comments
Open

【设计模式-创建型】简单工厂模式 #67

SilenceHVK opened this issue Jun 16, 2019 · 0 comments
Assignees

Comments

@SilenceHVK
Copy link
Owner

定义: 由一个工厂对象决定创建出哪一种产品类实例

类型:创建型,不属于 COF 23 种设计模式

适用场景:

  • 工厂类负责创建的对象比较少;
  • 客户端(应用层)只知道传入工程类的参数,对于如何创建对象(逻辑)不关心;

优点:

只需要创建一个正确的参数,就可以获取所需的对象,而无需知道其创建细节。

缺点:

工厂类的职责相对过重,增加新的产品需要修改工厂类的判断逻辑,违背开闭原则。

UML 图:

Simple Factory

示例代码:

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

    public Product getProduct(string className){
    
        if("productA".equalsIgnoreCase(className)){
            return new ProductA();
        }else if ("prodctB".equalsIgnoreCase(className)){
            return new ProductB();
        }
        
        return null;
    }
    
    public Product getProduct(Class c){
    
        try{
            return (Product) Class.forName(c.getName()).newInstance();
        } catch (Exception e){
            e.printStackTrace();
        }
        
        return null;
    }
}
  • Client
public class Client {
    public static void main(String [] args){
    
        ProductFactory productFactory = new ProductFactory();
        
        Product productA = productFactory.getProduct("productA");
        
        Product productB = productFactory.getProduct(ProductB.class);
        
    }
}
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