The Factory Method Pattern of Design Pattern-Simple Implementation

Factory method pattern

Simple factory pattern,
abstract factory pattern,
abstract factory, simple implementation of database connection pool

1. Definition:

Refers to the definition of an interface for creating objects, but the class that implements this interface decides which class to instantiate, and the factory method puts the instantiation of the class in the subclass.

2. Advantages:

If the creation logic of each object is different, the responsibilities of the factory will become more and more, and it is not easy to maintain. The factory method pattern has a dedicated factory for each object.

3. The four roles of the factory method pattern

Abstract factory : The core of the factory method pattern, in which any factory that creates objects must implement this interface.

Concrete factory : The concrete factory class that implements the abstract factory, contains the logic for creating objects, and is called by the application to create objects.

Abstract object : the superclass of the object created by the factory method pattern

Concrete object : It implements the interface defined by the abstract object role, and an object is created by a concrete factory.

4. Simple implementation of factory method pattern
public interface IFactory {//抽象工厂
	IProduct makeProduct();	
}
public class FactoryA implements IFactory {//创建A产品的工厂
	@Override
	public IProduct makeProduct() {
		return new ProductA();
	}
}
public class FactoryB implements IFactory {//创建B产品的工厂
	@Override
	public IProduct makeProduct() {
		// TODO Auto-generated method stub
		return new ProductB();
	}
}
public interface IProduct {//抽象对象
	void doSomeThing();
}
public class ProductA implements IProduct {//具体对象A
	@Override
	public void doSomeThing() {
		// TODO Auto-generated method stub
		System.out.println("A");
	}
}
public class ProductB implements IProduct {//具体对象B
	@Override
	public void doSomeThing() {
		// TODO Auto-generated method stub
		System.out.println("B");
	}
}
public class Client {
	public static void main(String[] args) {		
		IFactory factoryA = new FactoryA();//创建A工厂创建
		IFactory factoryB = new FactoryB();//创建B工厂创建
		IProduct productA = factoryA.makeProduct();//A工厂创建A对象
		IProduct productB = factoryB.makeProduct();//B工厂创建B对象
	}
	
}

Guess you like

Origin blog.csdn.net/weixin_45355510/article/details/112645330