Learning and realization of simple factory model

Simple factory pattern

The simple factory pattern (simpleFactory) is used to solve the problem of object instantiation. There is a factory class, which dynamically determines the instance to be created based on the parameters, which is the algorithm you want to implement. You don't need to know how he achieved it.

Features:

  1. Multiple similar subclasses inherit the same parent class and operate on the variables in the parent class
  2. The factory class is responsible for the logic of creating an instance
  3. When there are too many subclasses, it is not recommended to use the factory pattern

Example: If you want to buy things in the factory, you provide the factory with information about the things you want to buy, and the factory will give you the things you want to buy. You don’t need to know how this thing is made.

Implementation

Worker.cs

class Worker
{
	//工人类
	private string occupation;

	public string Occupation{get=>occupation; set=>occupation=value;}

	public virtual void introduce()
	{
		Console.WriteLine("我是一名工人");
	}
}

Farmer.cs

class Farmer:Worker
{
	//工人的派生类:Farmer
	public override void introduce()
	{
		Console.WriteLine("我是一名{0}",Occupation);
	}
}

Doctor.cs

class Doctor:Worker
{
	//工人的派生类:Doctor
	public override void introduce()
	{
		Console.WriteLine("我是一名{0}",Occupation);
	}
}

WorkerFactory.cs

class WorkerFactory
{
	//工人工厂,创建工人
	public static Worker creatWorker(string occupation)
	{
		Worker worker = null;
		switch(occupation)
		{
			case "农民":
				worker = new Farmer();
				break;
			case "医生":
				worker = new Doctor();
				break;
		}
		return worker;
	}
}

Program.cs

class Program
{
	static void Main(string[] args)
	{
		Worker worker = creatWorker("农民");
		worker.Occupation = "农民";
		worker.introduce();
	}
}

to sum up

  1. The factory is a creation mode, and its role is to create objects;
  2. Violation of the principle of high cohesion responsibility distribution, the logic is in the same factory, so it can only be used in very simple scenarios
  3. To add a new subclass, it is necessary to modify the method in the factory

Guess you like

Origin blog.csdn.net/weixin_36382492/article/details/84788258