Seven principles of object-oriented js

Seven principles:

1: Single Responsibility Principle: a class is only responsible for a function

2: Richter substitution principle (LSP): subtype must be able to replace their parent type.

3: Open Closed Principle: open to extension, closed for modification.

4: Isolation Interface Principle: The client should not rely on its unwanted interfaces, a class dependent on another class should be based on the smallest interface

5: Dependency Inversion principle: high-level modules should not depend on low-level modules, both of which should rely on its abstract;

6: Dmitry principles: the principle of least know

7: combination aggregation multiplexers principle: When software reuse, to try to be implemented using a combination of association or polymerization, followed before considering the use of inheritance to achieve.

1: Single Responsibility Principle

Meaning: The reason for a class, there is only one cause of such changes; duty class is unique, and this duty is the only cause of other types of change.

Popular point, a class should do one kind thing; a class should only be responsible for a function.

Objective: to reduce code complexity, decoupling system, improve readability

for example:

A single principle to remember a word like, is 'a class is only responsible for one function'. For example, now we have to take pictures and play music two functions to be achieved. Is the wrong approach these two functions are packaged into a single class, the correct approach is to package two classes, to achieve a camera, a music player function implementation.

code show as below:

// 定义拍照类
class Photograph{
constructor(name){
this.name = name
}
photograph(){
console.log(`给${this.name}拍照`)
}
}
// 定义播放音乐类
class PlayMusic{
constructor(musicName) {
this.musicName = musicName
} 
outMusicName(){
console.log(`播放音乐${this.musicName}`)
} 
}

var photograph1 = new Photograph('小明');
var playMusic1 = new PlayMusic('爱我中华');
photograph1.photograph(); // 给小明拍照
playMusic1.outMusicName();// 播放音乐爱我中华

2: Richter substitution principle (LSP)

Definition: Substitution is the moral of this principle, all local reference to the parent class can be a subclass of substitution for him.

New to this principle, when really look ignorant force, replace subclass the parent class? Hell!

With my understanding explain:

This principle means that you instantiate an instance of a parent class, by this example implements a function, to ensure this function, through inheritance over this subclass the parent class of the instantiated instances, the same can achieve this function. (Purely personal understanding, not to be sprayed)

for example:

Birds have already defined a method to fly, and now the birds by instantiating an instance of a bird, call the fly method to achieve and let the bird fly 1 (which is a function).

Ostrich define a class, and an eagle classes inherit from birds. Such wording is a violation of our Richter substitution principle. Since your to instantiate an instance of a class by ostrich ostrich 1 is not used in Example 1 to replace the ostrich, the birds by the above example 1 Example of birds, as in Example 1 and ostrich no way to fly function , which violates the Richter replace function.

The correct approach is, you should create two parallel parent bird, fly and not fly, flying birds, birds inherit the parent class flying, flightless bird flightless bird inheritance the parent class.

// 定义会飞的鸟类
class CanFly{
constructor(name){
this.name = name
}
canFly(){
console.log(`我是${this.name} I can fly`)
}
}
// 定义不会飞的鸟类 
class NotCanFly{
constructor(name) {
this.name = name
} 
notCanFly(){
console.log(`我是${this.name} I not can fly`)
} 
}
// 定义老鹰类
class LaoYing extends CanFly{
constructor(name,color) {
super(name);
this.color = color
} 
color(){
console.log(this.color)
}
}
// 定义鸵鸟类
class TuoNiao extends NotCanFly{
constructor(name,color) {
super(name);
this.color = color
} 
color(){
console.log(this.color)
}
}

var laoYing1 = new LaoYing('老鹰一','白色');// 通过LaoYing类实例化老鹰1实例
var laoYing2 = new CanFly('老鹰二');// 通过会飞的鸟类实例化老鹰2实例

laoYing1.canFly()// 我是老鹰一 I can fly
laoYing2.canFly()// 我是老鹰二 I can fly

By the above example we can see that the Eagles 1 and 2 are not examples of eagle out by a class, but by a parent and a child out of the class is instantiated, but can be implemented fly function, this is the Richter Substitution principle.

3: Open Closed Principle

Vernacular means that when we change a software (such as expansion of other functions), should be achieved by changing the software scalable way, and should not modify the original code to implement change.

To put it plainly, it is that these entities need to perform various actions should be designed to require no modification can achieve a variety of changes, adhere to the principle of opening and closing in favor of the project with a minimum of code maintenance. I think that is a reflection of the principle of opening and closing of polymorphism. (Personal understanding, not to be sprayed.)

For chestnut:

// 定义大鱼类
class BigFish{
constructor(name) {
this.name = name
} 
eat(){
console.log(`我是大鱼我吃小鱼`)
}
}
// 定义小鱼类继承大鱼类
class SmallFish extends BigFish{
constructor(name) {
super(name)
} 
// 重写吃方法,小鱼类只能吃虾米
eat(){
console.log(`我是小鱼我吃虾米`)
}
}

4: Interface Segregation Principle

Meaning: The client should not rely on its unwanted interfaces, a class dependent on another class should be based on the smallest interface.

For chestnut:

There is now a test class with test interfaces above are the test Yushu Wai, physics and chemistry, political history and geography and other interfaces. There are arts students and science classes students classes inherit the exam class, the class that implements the interface test conducted examinations. Here is some violation of the principle of the interface isolation, because liberal arts students do not need to test physicochemical, science students also do not need to test the political history and geography.

solve:

Examination of the interface refinement, examination interfaces arts and sciences test interfaces; raw arts, science students each implement additional test interfaces arts, science test interface.

// 文科考试接口
class ArtsExam{
constructor(name) {
this.name = name
}
exam() {
console.log(`我是${this.name}我要参加考语数外历史地理政治`)
}
}
// 理科考试接口
class ScienceExam{
constructor(name) {
this.name = name
}
exam() {
console.log(`我是${this.name}我要参加考语数外物理化学生物`)
}
}
// 文科学生
class Arts extends ArtsExam{
    constructor(name){
       super(name)
  } 
}
// 理科学生
class Science extends ScienceExam{
constructor(name){
super(name)
}
}

student1=new Arts("文科生小红")
student1.exam()// 我是文科生小红我要参加考语数外历史地理政治

student2=new Science("理科生小明")
student2.exam()// 我是理科生小明我要参加考语数外物理化学生物

5: Dependency Inversion principle

The essential:

High-level modules should not depend on low-level modules, both of which should rely on abstract
abstract should not depend on the details of
the details should depend abstract
Objective: To avoid changes in demand resulting in excessive maintenance work

Explanation: The program is simply to rely on the abstract interface, do not depend on the specific implementation. Requirements for abstract programming, not to implement programming.

For chestnut:
existing a human, a human interface to read, because reading is, so to rely on a method for outputting content book book class. This violates the Dependency Inversion Principle, this time because you are human high-level module, the book is the low-level modules, high-level module Humans depend on low-level modules books category. At this point if you want human beings to read the newspaper, the original reading is very difficult to do.

solve:

// 阅读类
class Reader{
constructor(content) {
this.content = content
}
// 获取内容的抽象方法
outPutContent(){
throw "Abstract methods require concrete implementation";
}    
}

// 书类
class Book extends Reader{
constructor(content) {
super(content)
}
// 获取内容的抽象方法的实现
outPutContent(){
console.log(`书的内容是${this.content}`)
}
}
// 报纸类
class NewsPaper extends Reader{
constructor(content) {
super(content)
}
// 获取内容的抽象方法的实现
outPutContent(){
console.log(`报纸的内容是${this.content}`)
} 
}

// 人类
class People{
constructor(name) {
this.name = name
}
// 读抽象方法的具体实现
reader(what){
console.log(`${this.name}读的`,what.outPutContent())
}    
}

let xiaoMing = new People('小明')
let xiaoHong = new People('小红')
let anTuSheng = new Book('安徒生故事')
let wanBao = new NewsPaper('今日晚报')

xiaoMing.reader(anTuSheng);// 书的内容是安徒生故事 小明读的
xiaoMing.reader(wanBao);// 报纸的内容是今日晚报 小明读的

xiaoHong.reader(anTuSheng);// 书的内容是安徒生故事 小红读的
xiaoHong.reader(wanBao);// 报纸的内容是今日晚报 小红读的

Above to achieve the implementation of the Dependency Inversion principle.

6: Dmitry principle

Demeter is the practice of the concept of decoupling between classes, weak coupling. If the degree of coupling between the high class and class, when a class is changed, and he will change the relationship between the classes. This is very conducive to the expansion and maintenance, plus late when we need or demand change, the code is difficult to write.

For chestnut:
now a guest of the class, guests ordered a dish of scrambled eggs and tomatoes. This class cook tomato scrambled eggs need to do. To cut class chefs such as tomatoes, beat eggs, fried, salt several methods to complete the dish, and the dishes to the guests. Demeter principle is embodied here, guests ordered food, then cook the beginning of dishes to the guests, the guests cook the dish during ye do absolutely need to know.

// 客人类
class Guest{
constructor(name) {
this.name = name
}
// 点菜方法
orderDishes(val){
console.log(val.outPutDishes())
}
}
// 厨师类
class Chef{
// 切西红柿
cutTomatoes(){
console.log('切西红柿')
}
// 打鸡蛋
hitEgg(){
console.log('打鸡蛋')
}
// 放盐
putSalt(){
console.log('放盐')
}
// 给客人菜方法
outPutDishes(){
this.cutTomatoes();
this.hitEgg();
this.putSalt();
console.log()
return '西红柿炒鸡蛋'
}
}
let xiaoMing = new Guest('小明')
let chef1 = new Chef()
xiaoMing.orderDishes(chef1)

7: Principles multiplexing polymerizable composition

Polymerization (Aggregation) shows a weak 'own' relationship, the relationship between the overall and individual, i.e., has-a relationships, in which case the entire portion between the separable and are, they may have their own life cycle.

Synthesis of (Composition) it is a strong 'own' relationship, the relationship of his reflects contains-a, this relationship more than polymerization, also called polymerization strong. It reflects a strict relationship between the parts and the whole, the parts and the whole life cycle of the same.

Polymerizable composition multiplexing principles known synthetic multiplexing principle, a new object is in use in some existing object by association (combination relation, the relationship between the polymerization), to become part of the new object; new object call by delegating existing methods of an object to achieve the purpose of the alternate functions. Briefly, the way to make use of a combination of the polymerization / instead of inheritance.
For chestnut:

Guess you like

Origin www.cnblogs.com/zhengyufeng/p/11058046.html