設計模式篇(3) 設計原則
阿新 • • 發佈:2022-04-20
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 {
}
//從弱到強 依賴>關聯>聚合>組合