Why design patterns? Let's take a look at the six principles and use the design pattern principles.

Source: Internet
Author: User

Why design patterns? Let's take a look at the six principles and use the design pattern principles.

Introduction                                       

I don't like reading books very much, because I forgot to read ten lines of books, so I read the left teacher and copied it to improve my memory.

This is the http://www.cnblogs.com/zuoxiaolong/p/pattern1.html of old brother left

Directly go to the topic, I believe everyone has entered this line, almost all busy, but still want to power off in idle time. I always want to charge myself, and it takes a lot of time. However, I don't have to play the last two games, so I can rest my brain, but once I play the game, I won't be able to stop, if I had learned java by playing the game, I was so familiar with this sentence. No matter what, I should read the design pattern first.

Ps is above all nonsense

Learning the design model is to make us more professional. Yes, we are professional coder.

Subject

Before learning the design model, we need to first understand the six principles, which seem very reasonable.

① Single principle:

Only one thing.

I will use a pseudocode to express it.

// Class Calculator {
// Add
Public int add () throws NumberFormatException, IOException {File file = new File ("E:/data.txt"); BufferedReader br = new BufferedReader (new FileReader (file )); int a = Integer. valueOf (br. readLine (); int B = Integer. valueOf (br. readLine (); return a + B ;}
 }

If someone encapsulates such a class, and then you use it, how can we just add a slot without subtraction and multiplication? Do you need to copy it and change the "+" symbol to another symbol.

Q: Where does this class violate the single principle?

Let's take a look at why we use this computing class and calculate the sum

The procedure is as follows:

① Get File Content

② Calculate the return value

This class has two responsibilities at the same time.

Q: What problems does this class have?

At the early stage of development, we are likely to perform a large number of copies for the sake of speed, which leads to a lot of code duplication. In this way, we may write a subtraction or multiplication method, to copy and modify the code in addition.

Next we need to modify the above Code

// Get File content class Reader {int a, B; public Reader (String path) throws Exception {BufferedReader br = new BufferedReader (new FileReader (new File (path ))); a = Integer. valueOf (br. readLine); B = Integer. valueOf (br. readLine) ;}int getA () {return a ;}int getB () {return B ;}// separate calculation class Calculator {int add (int, int B) {return a + B;} int subtract (int, int B) {return a-B ;}}

This is simple, clear, and profound. Of course, these are what I copied. Sometimes there is no need to write some code on your own and follow your predecessors to take you a lot of detours, sometimes I always follow my own path. Although I get more, not everyone is like this. I am the former, and I understand my shortcomings.

    

② Lee's replacement principle

The subclass should be able to replace the parent class and work normally.

Generally, subclass methods of the parent class should not be overwritten, because the methods of the parent class are generally made public.

However, in actual development, we may often rewrite the methods of the parent class for convenience, which leads to different functions of the Child class and the parent class,

The following code is used to describe:

// Parent class FatherClass {public void eat () {System. out. println ("My favorite rice ");}}
// Subclass
Class SonClass extends FatherClass {void eat () {System. out. println ("I don't like rice");} class SomeoneClass {@ Test public void runLiSi () {FatherClass fc = new FatherClass (); SonClass SC = new SonClass (); fc. eat (); SC. eat ();}}

In the above example, the parent class and the Child class do the same thing, but the result is indeed the opposite.

This principle is to constrain us. When such a situation occurs, we need to consider whether or not it works.

 

③ Interface isolation principle (interface minimization principle)

During development, we often find that many methods are empty while implementing an interface.

Directly Add code

 

// Mobile interface public interface BaseMobile {public void call (); // call public void sendSms (); // send a text message public void playBird (); // play the game}

 

As long as it is a mobile phone, you should have the function of sending text messages by phone, but the function of playing games is not necessarily available on every mobile phone.

Therefore, we can first remove the game play interface to minimize this interface.

// The modified code public interface BaseMobile {public void call (); public void sendSms ();} // adapter public interface IOSMobile extends BaseMobile {public void playBird ();}

In this way, we can clearly understand the principle of minimizing interfaces,

But there are special cases in everything,

Do cell phones that do not require the text message function exist? Obviously, they exist. similarly, with the rapid development of the times, the basic functions of mobile phones are changing. Just like this, a mobile phone should be able to access the Internet.

Ps: Here, I obviously feel that my way of thinking is changing. Our code should follow some of the specifications, we often change people's way of life while code is inseparable. A beautiful life consists of code. In the future, our code may be like science, everyone should know her and learn from her.

 

④ Principle of dependency inversion

High-level modules should not depend on the underlying modules. Both of them should depend on abstraction, abstraction should not rely on details, and details should depend on abstraction.

The meaning of this sentence is that whether you are from Beijing or from Chaoyang in Beijing, you are all Chinese. In fact, I still feel better at understanding this sentence.

The following code is used for representation.

 

// Abstract person public interface People {void myInfo (); // self-introduction void canDo (); // what can be done} // Chinese public class China: people {public void myInfo () {System. out. println ("I am a Chinese");} void canDo () {System. out. println ("I Will code, move bricks, repair cars, drive cars, funny") ;}// American public class America: People {public void myInfo () {System. out. println ("I am an American");} void canDo () {System. out. println ("I Will code, mygod, yea, aye, huhuh") ;}// high-level public class PeopleInfo {private People people; public PeopleInfo (People people People) {this. people = people;} public void myInfo () {people. myInfo ();} void canDo () {people. canDo ();}}

 

Currently, the PeopleInfo class depends on People, and the specific method does not affect PeopleInfo. You only need to change the implementation of People, that is, the details depend on abstraction.

And PeopleInfo does not depend on China and America, that is, the dependency is put upside down.

Here, I will explain that some people may not be very clear about the dependency inversion.

PeopleInfo depends on People. When we need PeopleInfo to do something, we need to inject China or other implementation classes, but PeopleInfo does not depend on China,

PeopleInfo only depends on People.

Imagine the result of using PeopleInfo, injecting China, and using myInfo (): I am china. Injecting America, and using myInfo (): I am America.

Q: It indicates that PeopleInfo does not rely on China and America, but how can we call them?

In turn, there are two methods to use the China myInfo () method.

First, is new a little rough?

Second, inject China into the PeopleInfo professional code.

The second type of China depends on PeopleInfo, Which is reversed. This is my current understanding. If you have any problems, you can point it out.

 

 

⑤ Dimit principles

The principle of least understanding is that a class should not know too many things of other classes as much as possible, and should not have too many contacts.

In the vernacular, a class should not depend on too many details of other classes, and other classes should not provide too many details, such as high cohesion and low coupling.

First, it does not conform to this principle.

 

// Low cohesion public class LowCohesion {private String name; private int age; private boolean openMouth = false; public LowCohesion (String name, int age) {this. name = name; this. age = age;} public void setOpenMouth (boolean boo) {this. openMouth = boo;} public saySelf () {if (openMouth) {System. out. println ("Hello everyone, my name is" + name + ", this year" + age + "");} else {System. out. println ("...... ") ;}}// client public class client {public static void main (String [] args) throws Exception {LowCohesion lc = new LowCohesion (" elder brother ", 26 ); // come to lc. setOpenMouth (true); // Lao Ge zhangkou lc. saySelf (); // speaking }}

 

Assume that we are the interviewer and come to the individual. Generally, we only need to introduce ourselves, that is, saySelf. In this example, we need openMouth. This class should not depend on other classes for too many details.

 

This action can be an external drive, but it is completely unnecessary to expose the details. We want to introduce ourselves, instead of allowing you to speak first, and then you can introduce yourself, the saySelf action should be embedded with openMouth, that is, other classes should not provide too much details.

My expression may not be very accurate. In terms of the dimit principle, I understand the two-way constraint rules, mainly for class cohesion.

⑥ Principle of opening/closing

Disable modifications and develop extensions.

In actual development, due to various scenario requirements, we need to modify a large amount of original code. Many projects are very fast and scalable. The project can be expanded when it is opened.

Sometimes I feel like I can control one party, but I really don't understand anything. I feel like my predecessors again, and I will stick to it.

    

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.