To summarize the builder model is to combine different independent components under certain conditions to form a relatively business-complete object.Callers do not need to know the construction process.
We start by assembling computers
Let's start by buying an assembled computer.
First of all, to buy a computer, there are generally two choices - brand computer and assembly computer. In order to save time and rest assured, people will choose to buy brand computer (that is, the whole machine).Here, for a better analysis of the problem, assume that we decided to buy an assembly computer for cost-effective reasons.So what should we do?
First of all, what are the components of a complete computer?
After searching a part of the data, we found that the main components are motherboard, CPU, graphics card, display screen, memory bar, etc.It's just beginning. We just know that's not good. There are several brands of each hardware, to say nothing, and we certainly want the best price.So we also need to spend time looking for information about the brand's reputation for each component and the users'actual experience (such as Taobao's seller show, and some professional online reviewers' reports).
Okay, after that, it's time to decide how to match all kinds of hardware.But at last there was another problem. The hardware was bought back. We can't put these little whites in. We don't know where and how to put each part in the host box.What if the outfit breaks, isn't the money spent in vain.
After another twist and turn, the whole computer is finally assembled.Just as we raised our glasses to celebrate, we suddenly found a serious problem...
"My God, I can't turn it on yet. I need to install a system on my computer."
"Ah!!!"What can I do? I've been busy all day."
"What else can I do?Buy them all, install them all, only install the system."
"Yes, but I won't install the system, will you?"
"...Hmm~I won't either"
"Well, let's check the data and install the system."
The above story seems ridiculous and exaggerated to our ITer.But for computer whites, this is absolutely what happens.Because that's how I came from college.It took me a day just to reinstall the system.
But don't worry, a classmate in our next dormitory said in the morning that he would also buy an assembly computer.Let's go to see what he's doing now. To be honest, I hope he's going through all sorts of tortures as well as us, but I hope he's going to be as smooth as he is, so I can teach you how to install the system.
What?Started playing computer
When we entered the dormitory door, something stunning happened, and I found that he had started playing the League of Heroes, and that he had killed three times and successfully ended the game.
I immediately asked him how to get on the computer so quickly, and then I let go of my whole day.Only he laughed
"Now who can buy their own parts to install computers, even if you don't understand them yet."
"That's not what happens. Brand machines are much more expensive than assembly machines at the same price."
"Ha-ha, what a fool you are. You can go to the computer city and ask the boss to assemble it for you. You just need to pay some manual fees for it. It's not expensive."
"......"
Start to check seating
The first story is essentially equivalent to some of the problems we might face if we didn't develop in the builder model.In order to generate a business object (to assemble a computer), we have to spend a lot of time and energy collecting the member information (components) of the business object.So many objects are all organized by me (the client), which results in strong coupling and, most likely, an entire functional exception (forgotten to install the system, unequal memory bar models) due to small changes in requirements.This wastes more time and energy, increasing our labor and economic costs.
The second story is completely different. I (user/client) don't need to care about the process of building business objects at all. I just need to find the owner (builder) of the computer city to look for objects.
The first premise is to have a rule to construct a correct business object (computer) based on (contract).
So in order to assemble the computer in the right position, we have defined some necessary members (hardware)
public interface IFullComputer { string Mainboard { get; } string CPU { get; } string Disk { get; } string Graphics { get; } string Display { get; } bool HasOperatingSystem { get; } }
Now that it represents a complete and correct computer, let's first see how our second story calls the results.
public class Client { // Give it to the computer city owner private void IWantBuyComputer() { // Meet your boss var boss = new ComputerCityBoss(); // Tell the boss what computer I want to configure, and use the one recommended by the boss from the start var computerBuilder = new DefaultFullComputerBuilder(); var computer = boss.TellMeThenReturnComputer(computerBuilder); Console.WriteLine("Computer components complete, whether the system is pre-installed:" + computer.HasOperatingSystem); } }
Client (user) is very simple, just like many people buy computers now, go to the computer city to configure the computer you match with your boss, and then wait for the boss to give you the assembled computer.You don't need to know the details of computer assembly at all.This allows separation of client and business data from code.
Now let's look at the implementation code.
public interface IFullComputerBuilder : IFullComputer { IFullComputer Create(); } public class DefaultFullComputerBuilder : AbstractFullComputerBuilder { protected override void SetCPU() { } protected override void SetDisk() { } protected override void SetDisplay() { } protected override void SetGraphics() { } protected override void SetMainboard() { } } // Boss works with Brand public abstract class AbstractFullComputerBuilder : IFullComputerBuilder { public string Mainboard { get; set; } = "Default brand motherboard"; public string CPU { get; set; } = "Default brand CPU"; public string Disk { get; set; } = "Default Brand Memory"; public string Graphics { get; set; } = "Default Brand Graphics Card"; public string Display { get; set; } = "Default Brand Display"; public bool HasOperatingSystem { get; set; } public IFullComputer Create() { SetMainboard(); SetCPU(); SetDisk(); SetDisplay(); SetGraphics(); InstallOperatingSystem(); if (!HasOperatingSystem) throw new InvalidOperationException("install faild: no operating system"); return this; } protected abstract void SetMainboard(); protected abstract void SetCPU(); protected abstract void SetDisk(); protected abstract void SetGraphics(); protected abstract void SetDisplay(); private void InstallOperatingSystem() { //if (!condition) return; HasOperatingSystem = true; } }
Your boss will assemble your computer at your request.Of course, if you don't have special requirements, the owner will default to the brand partners, which will make more profits.
public class ComputerCityBoss { public IFullComputer TellMeThenReturnComputer(IFullComputerBuilder builder) { return builder.Create(); } }
Come back. NETCore Source Learn More
We can learn to deepen our understanding of knowledge points by using the source code of some excellent frameworks.
Builder mode is common in.netcore.I believe many people know that the.netcore startup program is in Builder mode:
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }
IHostBuilder is one of the constructors.Let's look at the source code for the default implementer, HostBuilder:
public IHost Build() { if (_hostBuilt) { throw new InvalidOperationException("Build can only be called once."); } _hostBuilt = true; BuildHostConfiguration(); CreateHostingEnvironment(); CreateHostBuilderContext(); BuildAppConfiguration(); CreateServiceProvider(); return _appServices.GetRequiredService<IHost>(); }
Obviously, it does the same thing as we did earlier, AbstractFullComputerBuilder.In order to form a complete object, many modules are organized internally.The external client (Program) does not need to know the details inside it at all, it is only responsible for calling Builder.