JavaScript Design Patterns Classic - the six principles of object-oriented

file

Author | Jeskson
source | Dada front-end bistro

1

The main study six principles in JavaScript. So six principles still remember what is it? Six principles means: Single Responsibility Principle (SRP), the open closed principle (OCP), Richter Substitution Principle (LSP), Dependency Inversion Principle (DIP), the principle of separation of the interface (ISP), the principle of a minimum of knowledge (LKP).

Single responsibility principle
closed principle open
Richter substitution principle
Dependency Inversion principle
principle of separation of the interface
minimal knowledge of principles

So what is the single principle of duty it? Single Responsibility Principle, the English word is: single responsable princple, the principles embodied in an object or method is only one thing.

Former traveling very slowly, letter very far, just enough to love a person's life. "Once the Rise become slow, cars, horses, mail is slow, your whole life to love a person too good-looking former locks, keys have exquisite look, you lock up, people will understand" (an object or method only do one thing)

If a method bear a lot of responsibility, it happened in the process of changing needs, the need to rewrite the possibility of this method is very substantial.

Single Responsibility Principle, a class provides only one function, there is reason not to cause too much class change. From the front, a person in charge of two different tasks, task 1 and task 2, task 1 when adjustments need to do and need to do repair man, may affect the normal operation of the task 2, task 2 will result in no way carry out.

Follow the single responsibility principle, we can solve this from happening, respectively, so that two people were to do the task 1, task 2, 1 people to do the task 1, 2 people to do the task 2, so that when a task needs change, not It will affect the normal operation of the task 2, the same token, when the task needs to be done to modify 2, 1 people do have influence not happen.

Richter substitution principle: all references to the base class place to be able to use the object of its subclasses, once a game player A, it has a moves Z1, now put the moves to extend Z1, later expanded into a big move Z, its large Z trick moves from the original Z1 and Z2 composed of new features, new features and Z to complete by subclasses apprentice gamers for gamers B of a, then this subclass apprentice gamers B completed this new feature Z2 same time, it is possible the moves will affect the original Z1, moves which led to errors.

(Law of Demeter: only direct communication with friends), every object and other objects related coupling, as long as there is coupling between two objects, say a friend relationship between the two objects.

2

Open Closed Principle, classes, methods, etc. should open its extension, modification of its closure, be extended without modifying the premise extension development, when there are new needs arise, we can be a way to extend the existing , the object has reached the other object; modified closed, the entity can not make any changes.

The method does not modify an existing function, you can implement various code changes.

// 定义一个方法
function da(x, y) {
 document.getElementById(x).style.color = y;
}

// 调用方法da
da('dashucoding', 'red');
// 开发封闭原则 -> 错误
// 定义方法
function da(x, y, z) {
 document.getElementById(x).style.color = y;
 document.getElementById(x).style.size = z;
}

// 调用方法da
da('dashucoding', 'red', '100px');
// 定义一个方法
function da(x, y) {
 document.getElementById(x).style.color = y;
}

// 不去动da这个方法
function dada(x, y, z) {
 da(x,y);
 document.getElementById(x).style.size = z;
}

// 正确使用开发封闭原则

function da(x, y) {
 document.getElementById(x).style.color = y;
}

da('dashucoding', 'red');

function dada(x, y, z) {
 da(x,y);
 document.getElementById(x).style.size = z;
}

dada('dashucoding', 'red', '100px');

Single Responsibility Principle, Profile, On a category, it should only be one the cause of change.

Open Closed Principle, Profile, software entity extension is open, but modification is off. That is up to expand its functionality without modifying a software entity basis.

Richter substitution principle, Profile, subclass must be able to replace their base class.

Dependency Inversion principle, the introduction of high-level modules should not depend on low-level modules, they should depend on abstractions. Abstract should not depend on the specific implementation, the specific implementation should depend on the abstract. Effect, reducing the coupling between the client and the implementation module.

Interface principle of separation profiles, using multiple specialized interface to replace a unified interface.

Synthesis of multiplexing principles, Introduction, is to use some existing objects in a new object inside, to become part of the new object; new objects by delegating these objects to achieve the purpose of reusing existing functionality. It is simply, to try to use a combination of, try not to use inheritance.

Demeter, Profile, also known as the principle of least knowledge, that an object should have as little understanding of other objects, do not talk to strangers.

3

Richter substitution principle, the principle is to develop a closed complement talking about the relationship between the base class and subclass. The most classic example of understanding the Richter substitution principle is "square is a rectangle", "ostrich not a bird," and so on, to get square, the math class, we know, a square is a rectangle, it is equal to a length and width rectangle, then it can be seen, it should be allowed to inherit from a square rectangle.

file

public class Rectangle {
 private int height;
 private int width;
 
 // 省略getter setter
}

// 正方形长和宽始终一样 覆写
public class Square extends Rectangle {
 @Override
 public void setWidth(int width) {
  super.setWidth(width);
  super.setHeight(width);
 }
 
 @Override
 public void setHeight(int height) {
  super.setWidth(height);
  super.setHeight(height);
 }
}
public class Test {
 public static void main(String[] args) {
  Test test = new Test();
   Rectangle rectangle = new Rectangle();
   rectangle.setHeight(5);
   rectangle.setWidth(4);
   test.zoom(rectangle, 2, 3);
   
   Square square = new Square();
   square.setHeight(5);
   square.setWidth(4);
   test.zoom(square, 2, 3);
 }
 
 public void zoom(Rectangle rectangle, int width, int height) {
  rectangle.setWidth(rectangle.getWidth() + width);
  rectangle.setHeight(rectangle.getHeight() + height);
 }
}

Dependency Inversion Principle, high-level modules should not depend on low-level modules, which should depend on the abstract. Abstract should not depend on the specific implementation, the specific implementation should depend on the abstract.

file

file

A high level block direction dependency hierarchy module, the module depends on the level of low-level modules. High-level and low-level not interdependent, any changes will affect low-level high-level module. Abstraction Layer, advanced level, implementation level, dependent on the specific implementation abstraction layer.

Interface separation principle, it should not rely on the client does not require an interface, a class dependent on another class should be based on the smallest interface. how to say?

There are three clients A, B, C are dependent on a larger interface, the larger interface has A (), B (), C (), but the client only need A A () only, the other not, the when you make use of the principle of separation interfaces A client needs only A (), so that the client need only B B (), so that the client need only C C ().

Design principle is the guiding ideology, ideologically give us in the right direction, programming, design patterns is a means to achieve, so the design mode is also comply with these principles. Reaches the high cohesion and low coupling, high cohesion to the internal module that is highly polymerized, the relationship between the inside of the module, said lower coupling is a coupling between the module and the module to be as low as possible, the relationship between the module and the module.

Single Responsibility Principle Summary: An object only one thing.

Open Closed Principle Summary: Open for extension, closed for modification.

Demeter, also known as the principle of least knowledge summary: An object must have a minimum understanding of other objects.

Design pattern and the intermediate pattern appearance model is an example of application of Demeter.

Dimitris method is simple, just talking with friends, do not speak to strangers. Drawback is that the system will generate a lot of small ways.

Synthesis of multiplexing principle, the use of the combination, less inheritance. Inheritance is a feature of object-oriented three, encapsulation, inheritance, polymorphism, inheritance simple, easy to expand, but also the succession, by the defect becomes the parent class, subclass must change, inherited break encapsulation, is the parent class, its implementation is transparent to the subclass, a relationship of inheritance is strongly coupled.

Variable parent class, subclass must change; inherited break encapsulation (subclass is encapsulated, due to changes in the parent class, resulting in destruction of the parent package subclass), for subclasses, the parent class by inheritance, there is no safety and security, parent modify its contents, it will lead subclasses functionally disrupted; the parent class, the subclass inherits the parent class, rewriting its methods, the parent class is not any modification.

Design Principles:

Single Responsibility Principle, a method only one thing; Richter substitution principle, subclass can substitute parent; Dependency Inversion principle, rely only on the interface method does not rely on, do not care about the underlying implementation method; the principle of separation of the interface, the large interface split into small interface; Demeter, function parameters passed as possible, open the closure principle, open for extended, closed for modification.

5

Single principle functions, advantages: reduce the complexity of a single class or object, in accordance with the principle of single responsibility to the object into smaller units, facilitate code reuse, but also conducive to unit test, when a duty needs to be changed , it does not affect other duties. Disadvantages: increase the complexity of coding, while increasing the difficulty of the association between objects.

Understanding with different responsibilities for different classes. Only a class bear a responsibility.

Minimum knowledge principles, advantages: reducing or eliminating the degree of coupling between objects, increase reusability. Disadvantages: object or package is the introduction of a third party objects to handle the relationship between the two, and sometimes third party objects can be complex and complicated that it is difficult to maintain.

Open Closed Principle, advantages: high stability of the program, where it can change after the separation easier to maintain.

// 单一职责原则
// 类
public class People {
 public void work() {
  System.out.println("work");
 }
 public void eat() {
  System.out.println("eat");
 }
 public void play() {
  System.out.println("play");
 }
}
// 一个类, 三个职责
// 单一职责原则
public interface workInter {
 public void work();
}
public interface eatInter {
 public void eat();
}
public interface playInter {
 public void play();
}
// 继承接口
public class People implements workInter, eatInter, playInter {
 public void work() {
  System.out.println("work");
 }
 public void eat() {
  System.out.println("eat");
 }
 public void play() {
  System.out.println("play");
 }
}
public class Test {
 public static void main(String args[]) {
  People people = new People();
  workInter worker = new People();
  worker.work();
  
  eatInter eater = new People();
  eater.eat();
  
  playInter player = new People();
  player.play();
 }
}

Richter substitution principle, any references to base classes must be able to transparently use objects in its child class, subclass must fully realize the function of the parent class, wherever the parent class appears, replace the subclass is no problem.

Richter substitution principle, I like animals, then I must love dogs, because dogs are a subclass of animal; but I said I like dogs, can not say I like animals, because I do not like other little small animals.

The subclass must fully realize the function of the parent class, for example unfulfilled:

// 父类
public abstract class Father {
 // work
 public abstract void work();
}
// 子类
public class Child extends Father {
 @Override
 public void work() {
  // 实现了这个方法,但功能不实现,什么都不做
 }
}

Dependency Inversion Principle, understood as the use of the interface or is an abstract class. Dependencies between modules occurs through the abstract, is not directly dependent on the relationship realized between classes, the class is achieved by dependency abstract class interface or generated abstract class interface or implementation-dependent type, it depends on the implementation class interface or is an abstract class.

public class Da {
 private Dada dada = null;
 public Da(Dada dada) {
  this.da = da;
 }
}

public interface DaInter {
 public void setDa(Dada dada);
}

public class Da implements DaInter {
 private Dada dada = null;
 public void setDA(Dada dada) {
  this.da = da;
 }
}

Interface Segregation principle, if a class implements an interface, but this interface has its methods do not, you need to split this interface, the method it needs to form a new independent interface to the class to implement.

Singleton: only one instance of a class, use a variable to distinguish whether the current instance is created through

// 一个参数,一个变量
var da = function (name) {
 this.name = name;
 this.instance = null;
}
da.prototype.getName = function() {
 alert(this.name)
}
da.getInstance = fucntion(name) {
 if(!this.instance) {
  this.instance = da(name);
 }
 return this.instance;
}

Recommended Reading

1, you know how much this, new, bind, call, apply? I tell you

2, why design patterns to learn JavaScript, because it is the core

3, an article to take you into JavaScript closures and advanced functions

4, in layman's language knowledge makers face questions in HR interview ES6

5, a JavaScript technology stack and take you through the prototype chain to inherit

On the current content of the article that is involved in front-end, PHP knowledge, if you are interested to follow, very honored, can you find really identify what the British! Also thank you for your attention in the coming days, hoping been quietly supporting me, I will try to write more good works. We grow together, learn from the zero-based programming, the user-friendly front-end Web presentation areas, data structures and algorithms, network theory, etc. to the junior partner. Share Web front-end related technical articles, tools, resources, course selection, hot information.


If this number of local contents do not get bits (for example: to copyright or other problems), please contact us for rectification can be timely and will be processed in the first time.


Please thumbs up! Because you agree / encouragement is the greatest power of my writing!

Welcome attention to Dada 's CSDN!

This is a quality, attitude blog

7d927f18ebd05ea1d505a572393fbc87.jpg

Guess you like

Origin www.cnblogs.com/dashucoding/p/11897006.html