设计模式清单
没有链接的是还没有写的,计划要写的,欢迎阅读交流~
前端设计模式(0)面向对象&&设计原则
前端设计模式(1)--工厂模式
前端设计模式(2)--单例模式
前端设计模式(3)--适配器模式
前端设计模式(4)--装饰器模式
前端设计模式(5)--代理模式
前端设计模式(6)--外观模式&&观察者模式
前端设计模式(7)--状态和策略模式
前端设计模式(8)--原型模式
...
什么是面向对象
把客观对象抽象成属性数据和对数据的相关操作,把内部细节和不想关的信息隐藏起来,把同一个类型的客观对象的属性数据和操作绑定在一起,封装成类,并且允许分成不同层次进行抽象,通过继承实现属性和操作的共享,来,前端设计模式我们从面向对象开始。
- 面向对象的分析 OOA
- 面向对象的设计 OOD
- 面向对象的编程 OOP
继承
/**
* 类 对象(实例)
* 父类Animal是公共的
*/
class Animal {
constructor (name) {
this.name = name
}
eat () {
console.log(`${this.name}eat`)
}
}
let animal = new Animal('动物')
animal.eat()
/**
* 继承
* 子类继承父类
* 继承可以把公共的方法抽离出来,提高复用,减少冗余
*/
class Animal {
constructor (name) {
this.name = name
}
eat () {
console.log(`${this.name}eat`)
}
}
class Cat extends Animal {
constructor (myname, age) {
super(myname)
this.age = age
}
speak () {
console.log(`${this.name}:喵喵~`)
}
}
let cat = new Cat('小花猫', 0)
cat.eat ()
cat.speak ()
复制代码
封装
这里说明一下, 把数据封装起来 减少耦合,不该外部访问的不要让外部访问 利于数据的接口权限管理 ES6 目前不支持,一般认为_开头的都会私有的,不要使用,后面讲的会使用ts,有不了解的童鞋可以去官网看看,2分钟入门
class Animal2 {
public name // 公共的,类内或者类外都可以访问,比如:你的名字谁都可以知道
protected age // 收保护的自己和自己的子类可以访问,比如:女性的年龄
private monney // 只有自己可以知道哦,私房钱嘛
constructor (name, age, monney) {
this.name = name
this.age = age
this.monney = monney
}
}
class Person2 extends Animal2 {
private card;
constructor(name,age,monney,card) {
super(name, age, monney)
this.card=card;
}
getName() {
console.log(this.name);
}
getAge() {
console.log(this.age);
}
getWeight() {
console.log(this.monney); // [ts] 属性“monney”为私有属性,只能在类“Animal2”中
}
}
let person = new Person2('dafei', 18, '100000', '金卡')
复制代码
多态
同一个接口可以不同实现
保持子类的开放性和灵活性
面向接口编程
class Animal {
public name;
protected age;
private weight;
constructor(name,age,weight) {
this.name=name;
this.age=age;
this.weight=weight;
}
}
class Person extends Animal {
private money;
constructor(name,age,weight,money) {
super(name,age,weight);
this.money=money;
}
speak() {
console.log('你好!');
}
}
class Dog extends Animal {
private money;
constructor(name,age,weight) {
super(name,age,weight);
}
speak() {
console.log('汪汪汪!');
}
}
let p=new Person('dafei',10,10,10);
p.speak();
let d=new Dog('dafei',10,10);
d.speak();
复制代码
设计原则
单一职责原则
- Single responsibility principle
- 一个程序只做好一件事
- 如果功能特别复杂就进行拆分
开放封闭原则
- Open Closed Principle
- 对扩展开放,对修改关闭
- 增加需求时,扩展新代码,而非修改已有代码
- 这是软件设计的终极目标
function parseJSON(response) {
return response.json();
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
const error = new Error(response.statusText);
error.response = response;
throw error;
}
export default function request(url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON)
.then(data=>{data})
.catch(err => ({ err }));
}
复制代码
单一职责原则
- Single responsibility principle
- 一个程序只做好一件事
- 如果功能特别复杂就进行拆分
其它原则
还有L 里氏替换原则、I 接口隔离原则、D 依赖倒置原则,JS使用比较少。
下一遍我们开始来一起学习,工厂模式