Simple factory ---- ---- factory method abstract factory pattern

Simple Factory

Specifically, the plant is not simply a model,
but a design idea ---- The business logic and interface logic separation, ie, separation of service and client
in the client does not need to be modified, modify server products increased class can be.
Specific practices:
1. Create a factory class as a parent class, product class as a factory class subclass specific product category as a product Subclass
2. factory class selection of different parameters depending on the client, establishing product function returns the product object is created, the product write a class method, the specific product class as embodied
server code:

服务端
public class Factory{
	// 工厂制作**相应的产品对象**
	public createProduct(int choose){
		HamburgerProduct hamburger = null;
		switch (choose){
			case "1":
			hamburger = new Hamburger_Spicy();
			break;
			case "2":
			hamburger = new Hamburger_Beef();
			break;
		}
		return hamurger;
	}
}
// 汉堡产品确定需要的动作
public class HamburgerProduct extends Factory{
	private double price;
	public double getPrice() {return price;}
	public double setPrice() {return price;}
	public void showInfo(){};
	
}
// 具体的汉堡产品实现具体的操作,比如实现价格显示,和价格初始化
public class Hamburger_Spicy extends HamburgerProduct{
	// 价格初始化
	public Hamburger_Spicy(){
		this.setPrice(18.0);
	}
	// 具体实现了展现信息
	@Override
	public void showInfo(){
		System.out.println("香辣汉堡的价格为" + this.getPrice());
	}
}
//具体的汉堡产品实现
public class Hamburger_Beef extends HamburgerProduct{
	// 价格初始化
	public Hamburger_Spicy(){
		this.setPrice(38.0);
	}
	// 具体实现了展现信息
	@Override
	public void showInfo(){
		System.out.println("牛肉汉堡的价格为" + this.getPrice());
	}
}

The client code:

public class Main{
	public static void main(String[] args){
		HamburgerProduct hamburger;
		//客户端输入具体的参数,就能获得相应的产品对象
		hamburger = Factory.createProduct(1);
	}
}

advantage

1. To achieve the objects created and used by separation (i.e. separation of business logic and interface logic) .
2. The client need not know the name of the class specific product category created just know the specific product class corresponding parameters can be.
3. By introducing the configuration file, you can replace and add new specific product category without modifying any client-side code and improve the flexibility of the system to some extent.
Shortcoming I will not say , because obviously, this is just a regular use of the idea , but the real works can not be so simple, and very many fatal shortcomings, this is not really design pattern.

Factory Method pattern

Published 19 original articles · won praise 4 · Views 483

Guess you like

Origin blog.csdn.net/qq_35050438/article/details/104095463