Factory (creative mode - factory mode)

Design pattern:
Solve the problem of changing requirements (used when you have a deeper understanding of software or module relationships).
Coupling relationship between modules:
(The coupling relationship directly determines the behavior of the software in the face of changes)
[Module division, find out what has changed and what has not changed]
Relationship between modules
(1) Tight coupling: When a module changes, all related modules Change (2) Loose coupling
: Some modules are easier to be replaced or changed, but other modules remain unchanged Primary and secondary relationship and abstract detail relationship .

insert image description here

Main module (main logic): changes slowly or remains unchanged [high-level abstraction]
secondary module (interface + implementation): changes quickly [lower level details]

Factory mode:
insert image description here
An object is being created: Due to changes in requirements, the specific implementation of the object often faces drastic changes, but the interface is stable.

Structure (combined with code is easier to understand):
insert image description here
code implementation example:
scene, frame of car and test car
1. Car abstract class:

public abstract class AbstractCar
{
    
    
    public abstract void Startup();

    public abstract void Run();

    public abstract void Turn();

    public abstract void Stop();
}

2. Car abstract factory

public abstract class CarFactory
{
    
    
    public abstract AbstractCar CreateCar();
}

3. Specific Hongqi brand vehicles and the factories of specific Hongqi vehicles

public class HongQiCar:AbstractCar//具体实现车
{
    
    
    private int Speed;
    public override void Startup()
    {
    
    
    }

    public override void Run()
    {
    
    
    }

    public override void Turn()
    {
    
    
    }

    public override void Stop()
    {
    
    
    }
}

public class HongQICarFactory:CarFactory//具体工厂
{
    
    
    public override AbstractCar CreateCar()
    {
    
    
        return new HongQiCar();
    }
}

3. Vehicle test framework

public class CarTestFramework
{
    
    
    public void BuildContext(CarFactory carFactory)//依赖接口
    {
    
    
        //需要多个实例
        AbstractCar c1 = carFactory.CreateCar();
        AbstractCar c2 = carFactory.CreateCar();
        AbstractCar c3 = carFactory.CreateCar();
    }
    public void DoTest()
    {
    
    
    }

    public void GetTestData()
    {
    
    
    }
}

4. Main function call

public static void Main(string[] args)
{
    
    
    CarTestFramework carTestFramework = new CarTestFramework();
    carTestFramework.BuildContext(new HongQICarFactory());
}

Main points:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_51565051/article/details/131420419