Elegant design mode - an object-oriented basis (on)

How to understand object-oriented

Abstract object-oriented features are encapsulation, inheritance, polymorphism based on the premise. Abstract rational analysis of the business from legitimate and reasonable understanding of the topic. The abstract should be reasonably self-consistent, easy to understand the relationship between the combination and aggregation: the core difference is the difference between life cycle. Combination relations overall and the individual as a whole, left the whole, the individual does not make sense, while producing, at the same time destroyed. Relationship polymerized, it is the presence of an individual separate part having the meaning of existence, even from the finishing, an individual may also be present separately. Do not abuse Inheritance: More inherit the role of time is the most basic concepts of object-oriented multi-state properties for two services: Classes and Objects

What is the distinction between "object-oriented programming," and what is "object-oriented programming language."

It is a specification or programming object-oriented programming style. It is an object of the class and the base unit code organization, and by abstraction, encapsulation, inheritance, polymorphism four most characteristic code design and implementation cornerstone

Object-oriented programming language syntax support mechanism classes and objects, and a ready-made syntactic sugar (grammar mechanism), can facilitate the realization of the four characteristics of object-oriented programming language programming to distinguish between what is "process-oriented programming" and what is "oriented Object programming "

    面向过程编程: 
        以动词为主,分析出解决问题所需要的步奏,然后用函数把这些步奏一步一步实现,使用的时候一个一个依次调用就可以了。
    面向对象编程:
        以名词为主,把构成问题事务分解各个对象,建立对象的目的不是为了完成一个步奏,而是为了描述某个事物在整个解决问题的步奏中的行为。

Object-oriented: the dogs (bones) process-oriented: eat (dog bones).

Object-oriented programming features Basic Principles

Package: The abstract attributes and methods packaged together and then to hide information, data protection

/*
    * @title 创建对象实现封装有四种方法
    * @method1 对象字面量方式{name: 'Mark_Zhang',key:'value'}  只能创建一次、复用率差、字面量多了代码冗余
    * @method2 内置构造函数创建 var parson =  new Object(); parson.name="内置构造函数创建对象"
    * @method3 简单的工厂函数 function createObj (name){let obj = new Object(); obj.name = name; return obj}
    * @method4  自定义构造函数
  */
  function Person (name, agei) {
    // 构造函数中多包含的属性和方法就可以理解抽象的一部分
    // public  公共属性
    this.name = name; // 实例可以直接通过对象点的方式直接访问
    // private  私有属性
    let age = agei;
    this.getAge = function(){
      return age;
    }
    this.setAge = function(a){
      age = a;
    }
  }
  Person.prototype.show = function(){
    return  this.name   ' 今年'   this.getAge()   '岁';
  }
  // 必须通过 new 关键字创建对象,否则 this 指向的就是 window 对象
  let p1 = new Person('Mark_Zhang',18)
  console.info(p1.name, p1.age) // Mark_Zhang undefined
  // 调用对象方法 (调用对象暴露的接口)
  p1.setAge(30);
  console.info(p1.getAge());
  // 调用原型方法
  console.info(p1.show())
  let p2 = new Person();
  // 利用对象动态性来添加属性
  p1.n = 'sunLine'
  console.info(p2.n) //sunLine
  
  /**
   * @title 通过【构造函数】和【原型法】添加成员的区别
   * @区别一: 通过【原型法】分配的函数(引用类型即可) 所有对象共享
   * @区别二: 通过【原型法】分配的属性( 基本类型)独立
   * @区别2.2: 我们还可以在类的外部通过. 语法进行添加,因为在实例化对象的时候,并不会执行到在类外部通过. 语法添加的属性,所以实例化之后的对象是不能访问到. 语法所添加的对象和属性的,只能通过该类访问。
   * @区别三: 若希望所有对象使用同一个函数,建议使用原型法添加函数,节省内存 
   * @区别四: 通过prototype给所有对象添加方法,不能访问所在类的私有属性和方法
   */

Abstract: How to Hide method implementation, so that the caller provides only those functions required relational approach, these features do not need to know specifically how to achieve. Inheritance: Inheritance is one of the biggest benefits of code reuse

Inheritance: subclasses can use all the functions of the parent class, and extend these features. Succession process, that is, from the general to the particular process.

A class inherited, inherited, a so-called Class is the prototype method used, the method to add on the prototype parent class, then the subclass prototype parent class object instance

// 声明父类
let SuperClass function  (){
  let id = 1;
  this.name = ["继承"];
  this.superValue = function () {
    console.info("superValue is true")
    console.info('id---->',id)
  }
}
// 通过原型给父类添加方法
SuperClass.prototype.getSuperValue = function() {
  return this.superValue();
}
// 声明子类
let SubClass = function () {
  this.subValue = function () {
    console.info("this is subValue")
  }
}
// 子类继承父类
SubClass.prototype = new SuperClass();
// 为子类添加公有方法
SubClass.prototype.getSubValue = function() {
  return this.subValue();
}
let sub = new SubClass(),
    sub2 = new SubClass();
    
sub.getSuperValue(); // superValue is true
sub.getSubValue(); // this is subValue
​
console.info(sub.id)  // undefined
console.info(sub.name) // 继承
​
sub.name.push('类式继承')
console.info(sub2.name) // ['继承','类式继承']

The core of which is a code SubClass.prototype = new SuperClass (); the role of the prototype object prototype object class method is to add a total of prototype for the class, after class but can not directly access these methods, only the class is instantiated, the new Copies created with the object properties and methods of the parent class constructor and prototype proto pointed parent class prototype object. So that subclasses can access the properties and methods of the parent class public and protected at the same time, private properties and methods of the parent class is not inherited by subclasses. Knock blackboard as the last paragraph of the code above, the use of the method of class inheritance, if there is a reference type constructor in the parent class, will be common to all instances of subclasses, therefore an instance of a subclass if the reference type is changed it will affect the instances of other subclasses. Constructors Inheritance

Officially because of the above-mentioned shortcomings, only the constructor inheritance, constructors inherited core idea is SuperClass.call (this, id), pointing directly change this, so that the properties and methods created by this copy in a subclass a, because it is a single copy, so that each instance of a subclass of each other. But it will result in a waste of memory problems

// SubClass.prototype = new SuperClass();
function SubClass(id) {
  SuperClass.call(this,id)
}

Classes inherit constructor subclass inherits the core idea is the prototype parent class object instance SuperClass.call (this, id) zodiac objects and advantages of the method of Example subclasses of the parent class prototype point

Each instance of a subclass of waste are possible interactions between individual memory independently of each other disadvantages subclass (subcolumn public attributes and methods in the superclass by adding prototype) combined inheritance

For the above two inheritance, combined the advantages of both inherited draw, i.e. to avoid the waste of memory, and such that each instance of a subclass of each other.

// 组合式继承
// 声明父类
let SuperClass = function(name) {
  this.name = name ;
  this.books = ['js','html','css']
}
// 声明父类原型上的f方法
SuperClass.prototype.showBooks = function(){
  console.info(this.books)
}
// 声明子类
let SubClass = function (name) {
  SuperClass.call(this,name);
}
// 子类继承父类(链式继承)
SubClass.prototype = new SuperClass();
​
let subclass1 = new SubClass('java');
let subclass2 = new SubClass('php');
subclass2.showBooks();
subclass1.books.push('ios');    //["js", "html", "css"]
console.log(subclass1.books);  //["js", "html", "css", "ios"]
console.log(subclass2.books);   //["js", "html", "css"]

Parasitic combination of inheritance

So the question again - combined inherited method is good, but can cause a problem, the parent class constructor will be created twice (call () time again, new time and again), so in order to solve this problem , there was a combination of parasitic inheritance. The key question is just the parent class constructor is created in the form of a combination of class inheritance and constructors twice in succession, but in the class hierarchy, we do not need to create the parent class constructor, we just want to subclass inherits the parent prototype to the class. So we created a prototype give the parent a copy, and then modify the subclass constructor property, and finally set up the prototype can be a subclass inherits // // prototype-style prototype-style class type is actually inherited inherited package implementation function returns one example, a modified example of the prototype inheritance incoming objects o

function inheritObject(o) {
    //声明一个过渡函数对象
    function F() {}
    //过渡对象的原型继承父对象
    F.prototype = o;
    //返回一个过渡对象的实例,该实例的原型继承了父对象
    return new F();
}

// // Parasitic Parasitic Inheritance is to inherit the inherited second prototype package, so that the prototype is equal to the prototype subclasses of the parent class. And during the second package in the object inheritance of the extension

function inheritPrototype(subClass, superClass){
    //复制一份父类的原型保存在变量中,使得p的原型等于父类的原型
    var p = inheritObject(superClass.prototype);
    //修正因为重写子类原型导致子类constructor属性被修改
    p.constructor = subClass;
    //设置子类的原型
    subClass.prototype = p;
}
//定义父类
var SuperClass = function (name) {
    this.name = name;
    this.books = ['javascript','html','css']
};
//定义父类原型方法
SuperClass.prototype.getBooks = function () {
    console.log(this.books)
};
​
//定义子类
var SubClass = function (name) {
    SuperClass.call(this,name)
}
​
inheritPrototype(SubClass,SuperClass);
​
var subclass1 = new SubClass('php')

Polymorphism: The biggest advantage is to improve the scalability and code reuse summary:

Package

What: hidden information, protect data access. How: limited exposure interfaces and properties, the need for programming language syntax to provide access control. Why: improve maintainability; reduce the complexity of the interface, improving ease of classes.

abstract

What: hide implementation, users only need to be concerned about function, without concern for implementation. How: by class or abstract class implements an interface, a special non-essential grammar mechanism. Why: improve the scalability of the code maintainability; reduced complexity, reduced the burden of the details.

inherit

What: represents the is-a relationship, divided into single and multiple inheritance. How: the need to provide special programming language syntax mechanism. For example, the Java "extends", C's ":." Why: to solve the problem of code reuse.

Polymorphism

What: subclass replacement parent class, subclass call implementation at runtime. How: the need to provide special programming language syntax mechanism. Such as inheritance, interfaces, classes, duck-typing. Why: improve code reusability and extensibility.

3W model is the key Why, no Why, the other two would be no meaning of existence. As can be seen from the four properties, the ultimate object-oriented only one purpose: maintainability. Easy to expand and easy to reuse, and the like belong to reduce the complexity of implementation maintainability.image

Published 35 original articles · won praise 64 · views 10000 +

Guess you like

Origin blog.csdn.net/tjx11111/article/details/104294110