1、什么是面向对象
概念:类、对象(实例)
// 类class Person {constructor(name, age) {this.name = namethis.age = age}eat() {console.log(`${this.name} eat something`)}speak() {console.log(`My name is ${this.name}, age ${this.age}`)}}// 实例化let zhangsan = new Person('zhangsan', 20)zhangsan.eat()zhangsan.speak()let lisi = new Person('lisi', 18)lisi.eat()lisi.speak()
三要素:继承、封装、多态
继承:子类继承父类
class Student extends Person {constructor(name, age, num) {super(name, age)this.num = num}studu() {console.log(`${this.name} is study`)}}let xiaoming = new Student('xiaoming', 18, 'A30')xiaoming.eat()xiaoming.speak()xiaoming.study()
封装:数据的权限和保密
// public 公共的// protected 受保护的// private 私有的用ts来编写demo// 如果变量前面没有修饰符,默认publicclass Person {nameageprotected weightconstructor(name, age, weight) {this.name = namethis.age = agethis.weight = 120}}class Student extends Person {num,private girlfriendconstructor(name, age, num) {super(name, age)this.num = numthis.girlfriend = 'xiaoli'}study(){console.log(`${this.name} is study`)}getWeight() {console.log(`${this.name} weight is ${this.weight}`)}}let zhangsan = new Student('zhangsan', 18, 'A3')console.log(zhangsan.girlfriend) // 报错,因为girlfriend是私有变量,不能被外部访问
多态:同一接口的不同实现
// 多态一般牵扯到重写、重载class Person {constructor(name) {this.name = name}saySomething() {}}class A extends Person {constructor(name) {super(name)}saySomething() {console.log('I A')}}class B extends Person {constructor(name) {super(name)}saySomething() {console.log('I B')}}// 这就是重写了父类的saySomething方法
2、为什么要使用面向对象
1、程序执行:顺序、判断、循环 — 结构化
2、面向对象 — 数据结构化
3、对于计算机,结构化的才是最简单的
4、编程应该简单 抽象
3、UML类图 — (Unified Modeling Language:统一建模语言)
画图工具:MS Office visio(微软的一个工具)、processon
注意:
+ :public# :protected- :private格式:属性名 类型+ name: String
关系:泛化(继承)、关联(引用)
class Person {constructor(name, house) {this.name = namethis.house = house}saySomething() {}}class A extends Person {constructor(name, house) {super(name, house)}saySomething() {console.log('I A')}}class B extends Person {constructor(name, house) {super(name, house)}saySomething() {console.log('I B')}}class House {constructor(city) {this.city = city}showCity() {console.log(`${this.city}`)}}// 测试let aHouse = new House('北京')let a = new A('aa', aHouse)console.log(a) // a有房子let b = new B('bb')console.log(b) // b无房子
4、设计原则
《UNIX/LINUX设计哲学》
- 准则1:小即是美
- 准则2:让每个程序只做好一件事
- 准则3:快速建立原型
- 准则4:舍弃高效率而取可移植性
- 准则5:采用纯文本来存储数据
- 准则6:充分利用软件的杠杆效应(软件复用)
- 准则7:使用shell脚本提高杠杆效应和可移植性
- 准则8:避免强制性的用户界面
- 准则9:让每个程序都称为一个过滤器
- 小准则1:允许用户制定环境
- 小准则2:使用小写,尽量简写
- 小准则3:寻求90%的解决方案
5、SOLID五大设计原则
S -- 单一职责原则(一个程序只做一件事)O -- 开放封闭原则(对扩展开放,对修改封闭)L -- 李氏置换原则(子类能覆盖父类,父类出现的地方子类就能出现)I -- 接口独立原则(保持接口的单一独立,每个接口应该是一种角色)D -- 依赖导致原则(面向接口编程,依赖于抽象不依赖于具体)
6、设计和模式是分开的
7、23种设计模式
一、创建型1、工厂模式2、单例模式3、原型模式二、结构型1、适配器模式2、装饰器模式3、代理模式4、外观模式5、桥接模式6、组合模式7、享元模式三、行为型1、策略模式2、模板方法模式3、观察者模式4、迭代器模式5、职责连模式6、命令模式7、备忘录模式8、状态模式9、访问者模式10、中介者模式11、解释器模式

