设计模式篇(3) 设计原则
作者:互联网
class AbstractDrink {
getPrice() {
return 1;
}
}
class Fanta extends AbstractDrink {
getPrice() {
return 5;
}
}
class CocaCola extends AbstractDrink {
getPrice() {
return 3;
}
}
class Sprite extends AbstractDrink {
getPrice() {
return 3;
}
}
class Customer {
drink(abstractDrink) {
console.log(abstractDrink.getPrice());
}
}
//里氏代换 可以替换, 任何可以传父类的地方, 都可以把子类传进去
//里氏代换是一个原则, 要求子类不能违反父类的功能和规定
let c1 = new Customer();
c1.drink(new Sprite());
c1.drink(new CocaCola());
c1.drink(new Fanta());
/**
* 倒置依赖原则
* 依赖抽象,而非依赖依赖具体的实现
*/
interface Girlfriend {
age: number;
height: number;
cook(): void
}
class LinZhiLing implements Girlfriend {
age: number = 35;
height: number = 178;
cook() {
console.log('泡面')
}
}
class HanMeiMei implements Girlfriend {
age: number = 35;
height: number = 178;
cook() {
console.log('泡面')
}
}
class SingleDog {
constructor(public girlfriend: Girlfriend) {}
}
let dog1 = new SingleDog(new LinZhiLing());
let dog2 = new SingleDog(new HanMeiMei());
interface Running {
run(): void
}
interface Flying {
fly(): void
}
interface Swimming {
swim(): void;
}
/*
胖接口
interface AutomobileInterface {
run(): void;
fly(): void;
swim(): void;
}
*/
//1,接口复用性高,2,耦合度低,3实现了单一职责
class Automobile implements Running, Flying, Swimming {
run() {}
fly() {}
swim() {}
}
class Salesman {
constructor(public name: string) {}
sale() {
console.log(this.name + '销售中....');
}
}
class SaleManager {
private salesman: Array<Salesman> = [new Salesman('张三'),new Salesman("李四")];
sale() {
this.salesman.forEach(salesman => salesman.seal());
}
}
class CEO {
private saleManager: SaleManager = new SaleManager();
sale() {
this.saleManager.sale();
}
}
class Category {
//也是关联 双向关联,互相关联
public products: Array<Product>;
}
class Product {
//产品类有一个实例属性是分类, 那么就认为产品关联了分类
//单向关联和双向关联
public category: Category;
}
class Class {
//一个班级里有很多学生,所以说聚合关系
public students: Array<Student>
}
class Student {
//如果是另外一个类是当前类的方法和属性或者是局部变量就是依赖关系
read(book:Book) {
let pen = new PerformanceNavigationTiming();
}
}
class Book {
}
class Pen {
}
class Heart {
}
class Person {
}
//从弱到强 依赖>关联>聚合>组合
标签:getPrice,原则,void,number,public,new,设计,设计模式,class 来源: https://www.cnblogs.com/guozhiqiang/p/16171481.html