How to explain the design pattern to the wife

Source: Internet
Author: User
Introduction

I have received a good response since I translated

What is the design pattern?

Shubho: Through our dialogue on the object-oriented design principle (oodp, I .e. the solid principle), I think you have a basic understanding of the object-oriented design principle (oodp. I hope you don't mind sharing your conversations on your blog. You can find it here:

Design Patterns are the standardized applications of these principles in certain public scenarios. Next, let's use some examples to learn what a design pattern is.

Farhana: Of course, I like examples.

Shubho: Let's take a car for example. A car is a complex object consisting of thousands of other objects, such as the engine, wheel, steering wheel, seat, car body, and other different parts or components.

Auto Parts

When assembling a car, the manufacturer needs to centralize and assemble different parts of these smaller self-contained car subsystems. These different widgets are also complex objects, and other manufacturers also need to produce and assemble them. When producing a car, the car company does not worry about how to assemble the parts (only if they want to ensure the quality of these objects/devices ). Of course, automakers are more concerned about how to assemble these different components to produce different models of cars.

Assemble different components according to different designs to produce vehicles of different models.

Farhana: Automobile manufacturing companies must have design drawings or blueprints for how to produce different models of automobiles, right?

Shubho: Of course, and these designs are good. They spend a lot of time and energy doing these designs. Once the design is complete, the production of cars is just like a gourd painting.

Farhana: Well. If there are some good designs in advance, you can follow these designs to produce different products in a short time, and the manufacturer does not need to re-design or re-invent the wheel each time a model product is produced, they only need to follow the existing design.

Produce different design drawings for different models of products (automobiles)

Shubho: You have caught the point. Now let's assume that we are a software manufacturer. We use different components or functions based on requirements to build different types of software.Program. When producing these different software systems, we often need to develop the same situation for different software systems.Code, Right?

Farhana: Yes. The same design issue is often encountered when developing different software programs.

Shubho: We try to develop software in an object-oriented way, and apply oopd to make the code easy to maintain, reusable, and scalable. Whenever we encounter these design problems, will it be better if we have a group of well-tested objects that have been carefully developed for use?

Farhana: Yes. This can save time, produce better software, and facilitate future maintenance.

Shubho: Good! In terms of design, it is advantageous that you do not need to develop those objects. After years of development, people have encountered some similar design problems and have formed some well-recognized and standardized design solutions. We call it a design pattern.

Thanks to the four groups, we have summarized 23 basic design patterns in design patterns: Reusable object-oriented software design. Four-person group by Erich
Gamma, Richard Helm, Ralph Johnson, and John vlissides. There are actually many object-oriented design patterns, but these 23 patterns are recognized as the basis of all other design patterns.

Farhana: Can I create a new mode? Is this possible?

Shubho: Of course, dear, why not ?! The design model was not invented by scientists. They are found. This means that there are some good design solutions in any general problem scenario. If we can point out an object-oriented design that can solve a new design-related problem, it will be a new design pattern defined by us. Who knows ?! If we find some design patterns, we may be called a two-person group one day, haha.

Fahana:

How will we learn the design model?

Shubho: I always think that examples are the best way to learn. In our learning method, we will not discuss the theory first and then discuss the implementation. I think this is a bad way. The design model is not a theoretical invention. In fact, the problem scenario first emerged, followed by the ins and outs and needs of these problems, followed by the evolution of some design schemes, and finally some of them were standardized as models. Therefore, we will try to understand and analyze some examples of the design patterns we discuss in real life, and then try to summarize a design step by step, and finally summarize some designs that match some patterns. Design Patterns are discovered in these similar processes. What do you think?

Farhana: I think this method is more useful to me. If I can draw a design pattern by analyzing the problem and summarizing the scheme, I don't have to memorize those design patterns and definitions. Proceed as you did.

A common design problem and its Solution

Shubho: Let's consider the following scenarios:

There are some electrical appliances (electric lights, fans, etc.) in our room ). These devices are laid out in some ways and controlled by the switch. You can replace or troubleshoot an electric appliance at any time without encountering anything else. For example, you can change an electric lamp without switching. Similarly, you can change the switch or troubleshoot it without encountering or replacing the corresponding electric lamp or fan. You can even connect the electric lamp to the switch of the fan, connect the fan to the power switch without the need to switch.

Electric Appliance: Fan and electric lamp

Two different switches for the fan and electric lamp, one common point and the other special point

Farhana: Yes, but that's it, right?

Shubho: Yes, it is. When different things are linked together, they should be linked in a certain way: modifying or replacing a system does not affect the other, or even if there is, it should be minimized. This makes your system easy to manage and costs low. Think about it. If you change the lights in the room and change the switch, would you be happy to spend money on your house and install the system?

Farhana: Of course not.

Shubho: Now, let's think about how the electric lamp or fan is connected to the switch to change one without affecting the other. What do you think?

Farhana: Wire used!

Shubho: Good. The layout of electric wires and appliances is associated with the electric lights/fans and switches. We can think of them as a bridge between different systems. The basic idea is that one thing cannot be directly connected with another thing. Of course, they should be linked through some bridges or interfaces. In terms of software, this is called "loose coupling ".

Farhana: I understand.

Shubho: Now let's try to deduce several key issues in the electric lights/fans and switch examples and try to deduce how they are designed and linked.

Farhana: Okay. Let's give it a try.

In this example, we have a switch, which may have several switches, such as common switches and beautiful switches. But they are usually switched, and each switch can be turned on and off.

So next we will have a switch base classSwitch:

    Public     class   switch {
Public void On () {
/// enable
}< br> Public void off () {
/// disable
}< BR >}

Next we can have some specific switches, such as a beautiful switch and a common switch. Of course,We will make the classFancyswitchAndNormalswitchNdInheritance classSwitch:

 
Public ClassNormalswitch: Switch {
}
Public ClassFancyswitch: Switch {
}

The two classes have their own characteristics and behaviors, but at this moment, we will simplify the following.

Shubho: Great. What should I do next?

Farhana: I will try. According to the oodp open and closed principle, we know that we should try to abstract as long as possible, right?

Shubho: Pair

Farhana: Unlike the switch, Fan and lamp are two different things. For the switch, we can use a switch base classSwitchBut the fan and lamp are two different things. The interface may be more suitable than defining a base class. Generally, they are all electrical appliances. So we can define an interface, suchIelectricalequipmentCan it be used as an abstract for electric lights and fans?

Shubho: Yes

Farhana: Well, each type of electrical appliance has the same functions. They can be turned on and off. Therefore, the interface may be as follows:

Public InterfaceIelectricalequipment {
VoidPoweron ();//Each electrical appliance can be opened
VoidPoweroff ();//Close each Electrical Appliance
}

Shubho: Great. You are very good at abstract things. Now we need a bridge. In reality, wires are bridges. In our object design, the switch knows how to turn on and off the appliance, and the appliance is connected to the switch in some way. There is no wire here, and the only way to connect the appliance to the switch is encapsulation.

Farhana: Yes, but the switch cannot directly know the fan or lamp. Switch should know an Electric ApplianceIelectricalequipmentCan be turned on or off. This means that,IswitchThere should beIelectricalequipmentInstance, right?

Shubho: Yes. An example of fan or lamp encapsulation is a bridge. So let's modifySwitchClass to encapsulate an electrical appliance:

   Public     Class  Switch {
Public Ielectricalequipment equipment {
Get ;
Set ;
}
Public Void On (){
// Switch on
}
Public Void Off (){
// Switch off
}
}

Farhana: Yes. Let's define real appliances: fans and electric lights. As I have seen, they are all electrical appliances, so they are implemented simply.IelectricalequipmentInterface.

Below are the fan categories:

   Public     Class  Fan: ielectricalequipment {
Public Void Poweron (){
Console. writeline ( " Fan open " );
}
Public Void Poweroff (){
Console. writeline ( " Fan off " );
}
}

The following is an electric lamp:

   Public     Class  Light: ielectricalequipment {
Public Void Poweron (){
Console. writeline ( " Turn on the electric light " );
}
Public Void Poweroff (){
Console. writeline ( " Light off " );
}
}

Shubho: Great. Now let the switch work. When the switch is turned on and off, it should be able to turn on and off the appliance (it is connected ).

The key points here are:

    • When the switch is enabled, the connected electrical appliance should also be enabled.
    • When the switch is down, the connected appliance should also be closed.

The rough code is as follows:

   Static     Void  Main (  String  [] ARGs ){
// Construction Electrical Equipment: fan, switch
Ielectricalequipment fan = New Fan ();
Ielectricalequipment light = New Light ();

// Construction Switch
Switch fancyswitch = New Fancyswitch ();
Switch normalswitch = New Normalswitch ();

// Connect the fan to the switch
Fancyswitch. Equipment = Fan;

// When the switch is connected to an electric appliance, the appliance should be turned on/off when the switch is turned on or off
Fancyswitch. On ();
Fancyswitch. Off ();

// Connect the electric light to the switch
Fancyswitch. Equipment = Light;
Fancyswitch. On (); // Turn on the light
Fancyswitch. Off (); // Turn off the lights
}

Farhana: Yes. The ON () method of the switch should internally call the turnon () method of the electric appliance, and the off () method should internally call the turnoff () method. Therefore, the switch type should be as follows:

   Public    Class  Switch {
Public Ielectricalequipment equipment {
Get ;
Set ;
}
Public Void On (){
Console. writeline ( " Switch on " );
Equipment. poweron ();
}
Public Void Off (){
Console. writeline ( " Switch off " );
Equipment. poweroff ();
}
}

Shubho: Good. This naturally allows you to switch the fan from one switch to another. But you can. This means you can change the switch of the fan or lamp without hitting the fan or lamp. For example, you can easily switch the lighting switch from fancyswitch to normalswitch, as shown below:

Normalswitch. Equipment=Light;
Normalswitch. On ();//Turn on the light
Normalswitch. Off ();//Turn off the lights

You can see that connecting an abstract electrical appliance to a switch (through encapsulation) will allow you to change the switch and electrical appliance without affecting the other party. This design is elegant and good. The four-person group is named: Bridge Mode.

Farhana: Great. I think I understand this. Basically, the two systems should not directly contact or depend on each other. Of course, they should be connected or dependent on abstraction (as described in dependency inversion and open closure), so they are loosely coupled, therefore, we can change our implementation as needed without affecting the rest of the system too much.

Shubho: You understand, dear. Let's take a look at the definition of the Bridge Mode:

" Separate the abstract part from the implementation part so that they can all change independently. "

You can see that our implementations follow this definition perfectly. If you have a class designer (such as Visual Studio or other ide environments that support this function), you will see similar class diagrams as follows:

Bridge Mode class diagram

Here,Invalid actionYesSwitch base classSwitch. RefinedmediaactionIs a specific switch class (Fancyswitch,Normalswitch And so on .).ImplementorYeselectrical InterfaceIelectricalequipment.Concreteimplementora And concreteimplementorbYesLightAnd Fan classFan.

Farhana: Just curious to ask you a question. As you said, there are many other design patterns. Why do you start with the bridge mode? Is there an important reason?

Shubho: This is a good question. Yes, I am in bridging mode, not starting with others for one reason. I think the bridge mode is the basis of all object-oriented modes. The reasons are as follows:

    • It teaches how to think about abstraction, which is a key concept of the object-oriented design model.
    • It implements the basic OOD principle.
    • It is easy to understand.
    • If you understand this mode correctly, it is easy to learn other models.

Farhana: Do you think I understand it right?

Shubho: I think you understand it very correctly.

Farhana: So what is next?

Shubho: By understanding the bridge mode, we just begin to understand the idea of the design mode. In our next conversation, we will learn other design patterns. I hope you will not feel bored with them.

Farhana: No. Believe me.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.