当前位置:网站首页>Talk about the composite pattern in C #
Talk about the composite pattern in C #
2022-06-23 04:59:00 【Dotnet cross platform】
Write it at the front
Composite Composite pattern is one of the most popular design patterns , I believe you are not so strange to it as to the visitor mode , After all, who has never encountered a tree structure . But the so-called review the old and know the new , Let's start with an example , Let's start with this model .
A simple example
Imagine that we want to establish a personnel structure of the company , In a company , We can simply divide into two types of employees , One is the manager ( Including the boss ), The other is grassroots employees , Managers can have subordinates , But ordinary employees can't , We write this code .
Grassroots employees
This kind of employee is the most basic employee , No subordinates
class BasicLevelEmployee // Grass roots staff
{
public string ID { get; set; }
public void ShowStatus(int indent)
{
string str = ID;
str = str.PadLeft(ID.Length + indent, '-');
Console.WriteLine(str);
}
}Managers
Managers can have subordinates , Subordinates may be grassroots employees , It could be another manager ( Consider the boss , No doubt other managers are subordinates to the boss ), Because there are more subordinates than grass-roots employees , So there are more methods to maintain subordinate attributes
class Manager // The manager
{
public string ID { get; set; }
public void ShowStatus(int indent)
{
string str = ID;
str = str.PadLeft(ID.Length + indent, '-');
Console.WriteLine(str);
indent += 4;
Subordinate.ForEach(s => s.ShowStatus(indent));
SubordinateManagers.ForEach(m => m.ShowStatus(indent));
}
public List<BasicLevelEmployee> Subordinate = new List<BasicLevelEmployee>();
public List<Manager> SubordinateManagers = new List<Manager>();
// Here are the methods that the manager belongs to
public void AddSubordinate(BasicLevelEmployee e) { Subordinate.Add(e); }
public void AddSubordinate(Manager e) { SubordinateManagers.Add(e); }
public void RemoveSubordinate(BasicLevelEmployee e) { Subordinate.Remove(e); }
public void RemoveSubordinate(Manager e) { SubordinateManagers.Remove(e); }
}Company structure
The company structure class is very simple , Just master the biggest BOSS, The personnel structure of the whole company can be displayed by following the vine
class CompanyHierachy
{
public Manager BOSS { get; set; }
public void ShowStatus()
{
BOSS.ShowStatus(0);
}
}Client code
Suppose the structure of the company is simple , Besides the boss, they are the development department and the finance department , Each department has its own manager , So we write the following code
class Program
{
static void Main(string[] args)
{
// Boss
Manager boss = new Manager() { ID = "BOSS" };
// Manager of development department
Manager devManager = new Manager() { ID = "Dev Manager" };
// Finance Manager
Manager financeManager = new Manager() { ID = "Finance Manager" };
// Development team leader
Manager devLead = new Manager() { ID = "Dev Lead" };
// Test team leader
Manager qcLead = new Manager() { ID = "QC Lead" };
boss.AddSubordinate(devManager);
boss.AddSubordinate(financeManager);
financeManager.AddSubordinate(new BasicLevelEmployee() { ID = "Purchase" });
devManager.AddSubordinate(devLead);
devManager.AddSubordinate(qcLead);
devLead.AddSubordinate(new BasicLevelEmployee() { ID = "Developer1" });
devLead.AddSubordinate(new BasicLevelEmployee() { ID = "Developer2" });
qcLead.AddSubordinate(new BasicLevelEmployee() { ID = "QuanityControl1" });
qcLead.AddSubordinate(new BasicLevelEmployee() { ID = "QuanityControl2" });
CompanyHierachy company = new CompanyHierachy() { CEO = boss };
company.ShowStatus();
}
}The code is very simple , No more explanation is needed , After running, we get the result

Everything is all right , The code works , The company structure has been established successfully .
Think again
But think about it , Is this code really good ? I think there are at least two things we can improve .
1. Grassroots employees and managers actually have too much in common ( Properties and methods ), You can use abstract thinking , Let them inherit from the same thing ?
2. In the manager class, we maintain multiple subordinate lists , If you add another intern later , Do we have to create more lists ? If we use inheritance , Will this problem still exist ?
Based on this , Use abstract thinking to make managers and employees inherit from the same class ( Employee ) Be imperative . After abstraction , The manager class inherits from employees and also contains a list of employees , It's probably the first time to see such a design method with its own parent list, which makes people feel uncomfortable , But don't worry , This is actually a common design method . This structure has both inheritance and composition , Is the essence of the composite pattern .
Refactoring using composite patterns
Composite pattern belongs to structural design pattern , It uses the type level and the aggregate level to construct larger composite structures
To put it more bluntly , When the local structure of the object is the same as the object itself , We can use inheritance plus aggregation to compose code , For example, in the example just mentioned

Observe , about Boss Come on , Its local structure , namely DevManager and FinanceManager What is the difference from its own structure ? They are all tree structures , It's just that the root node is different , Therefore, emotion and reason can be reconstructed by inheritance and aggregation .
So careful friends must have found , Some operations are unique to the manager class , Should we abstract these operations to the Employee class, which is the same parent class as the grass-roots employees ? For this question , There are generally two solutions .
Transparent type

In this design , The union of subclass methods is refined into a common parent class , Even if these methods do not need at all for some subclasses , The advantage of this is that the client does not need to know which subclass the object is entangled in when using , Transparent to the client , So the name . The current design mostly adopts this kind of .
Safe

The safety design is very conservative , It only refines the methods of the intersection of subclasses to the parent class , The advantage is absolute safety , The client can never be in BasicLevelEmployee Object AddSubordinate perhaps RemoveSubordinate. But sometimes we will face the situation of downward transformation .
Refactored code ( Transparent type )
Abstract out the common parent Employee class , Use transparent , All subclass methods are refined into this class
abstract class Employee
{
public string ID { get; set; }
public abstract void ShowStatus(int indent);
// Because it is transparent , Therefore, methods that are not used by grassroots employees will also be abstracted to the parent class
public abstract void AddSubordinate(Employee e);
public abstract void RemoveSubordinate(Employee e);
}For grassroots employees , If the client inadvertently calls a method that should not be used , This is basically a clear 、 A signal that there is a logical problem with the client code , In this case, an exception is thrown directly , Can expose problems more quickly
class BasicLevelEmployee : Employee
{
public override void ShowStatus(int indent)
{
string str = ID;
str = str.PadLeft(ID.Length + indent, '-');
Console.WriteLine(str);
}
public override void AddSubordinate(Employee e)
{
throw new NotImplementedException();
}
public override void RemoveSubordinate(Employee e)
{
throw new NotImplementedException();
}
}In the manager class , Thanks to the common parent class Employee, We can use a list to load all the subordinates , Whether subordinates are grassroots employees , Or the manager , Or interns that may be added in the future . After all, they are all employees
class Manager : Employee
{
public override void ShowStatus(int indent)
{
string str = ID;
str = str.PadLeft(ID.Length + indent, '-');
Console.WriteLine(str);
indent += 4;
Subordinate.ForEach(s => s.ShowStatus(indent));
}
public List<Employee> Subordinate = new List<Employee>();
// Here are the methods that the manager belongs to
public override void AddSubordinate(Employee e) { Subordinate.Add(e); }
public override void RemoveSubordinate(Employee e) { Subordinate.Remove(e); }
}The company architecture classes and client code calls remain unchanged , The running results are consistent , Refactoring successful .
You can see , After using the composite pattern , The current code not only eliminates redundancy ( No need to maintain multiple subordinate lists ), It also has the ability to resist future changes , Compared with the original structure , Of course, it is more reasonable . This is where structural design patterns come into play , Make the structure of objects more reasonable , Easier to expand .
This is about Composite Introduction to composite mode , In view of the limited ability of the author , If you have other opinions about what is said in this article , Feel free to leave a comment .
> author : Lao Hu writes code
> original text :https://www.cnblogs.com/deatharthas/p/16390116.html
边栏推荐
- 在Pycharm中使用append()方法对列表添加元素时提示“This list creation could be rewritten as a list literal“的解决方法
- win10查看my.ini路径
- FreeModBus解析1
- McKinsey: in 2021, the investment in quantum computing market grew strongly and the talent gap expanded
- STL tutorial 3- exception mechanism
- Abnova 荧光染料 510-M 链霉亲和素方案
- 聊聊 C# 中的 Composite 模式
- 云函数实现模糊搜索功能
- DPR-34V/V双位置继电器
- Alkylation process test questions and simulation test in 2022
猜你喜欢

Static two position relay gls-3004k/dc220v

Abnova 荧光染料 510-M 链霉亲和素方案

PCB -- bridge between theory and reality

ICer技能03Design Compile

A mvc5+easyui enterprise rapid development framework source code BS framework source code

Pads and flash symbols in cadence

Abnova ABCB10(人)重组蛋白说明书

DSP7 环境

laravel 8.4 路由问题,结尾处是编辑器左侧对照表,小白可看懂

Abnova fluorescent dye 510-m streptavidin scheme
随机推荐
ICER skills 03design compile
Abnova fluorescent dye 555-c3 maleimide scheme
Kail infiltration basic literacy basic command
一款MVC5+EasyUI企业快速开发框架源码 BS框架源码
TS advanced infer
Abnova酸性磷酸酶(小麦胚芽)说明书
Examples of corpus data processing cases (part of speech encoding, part of speech restoration)
智能语音时代到来,谁在定义新时代AI?
使用Live Chat促进业务销售的惊人技巧
在PCB板边走高频高速信号线的注意事项–高频高速信号设计基本原则
云原生数据库如荼如火,未来可期
Transformers中的动态学习率
Abnova fluorescent dye 510-m streptavidin scheme
2022 simulated examination question bank and answers for safety management personnel of metal and nonmetal mines (open pit mines)
FreeModBus解析1
WPF 基础控件之 TabControl样式
Abnova PSMA磁珠解决方案
20000 words + 20 pictures | details of nine data types and application scenarios of redis
Alkylation process test questions and simulation test in 2022
Dpr-34v/v two position relay