重學設計模式
讀Design pattern implementations in TypeScript筆記。
五種創造性設計模式
單例模式
namespace SingletonPattern {
export class Singleton {
// A variable which stores the singleton object. Initially,
// the variable acts like a placeholder
private static singleton: Singleton;
// private constructor so that no instance is created
private constructor() {
}
// This is how we create a singleton object
public static getInstance(): Singleton {
// check if an instance of the class is already created
if (!Singleton.singleton) {
// If not created create an instance of the class
// store the instance in the variable
Singleton.singleton = new Singleton();
}
// return the singleton object
return Singleton.singleton;
}
}
}
核心:維護一個實例,暴露統一的接口去獲取它,如果沒有則創建,如果有則直接返回。
抽象工廠模式
namespace AbstractFactoryPattern {
export interface AbstractProductA {
methodA(): string;
}
export interface AbstractProductB {
methodB(): number;
}
export interface AbstractFactory {
createProductA(param?: any) : AbstractProductA;
createProductB() : AbstractProductB;
}
export class ProductA1 implements AbstractProductA {
methodA = () => {
return "This is methodA of ProductA1";
}
}
export class ProductB1 implements AbstractProductB {
methodB = () => {
return 1;
}
}
export class ProductA2 implements AbstractProductA {
methodA = () => {
return "This is methodA of ProductA2";
}
}
export class ProductB2 implements AbstractProductB {
methodB = () => {
return 2;
}
}
export class ConcreteFactory1 implements AbstractFactory {
createProductA(param?: any) : AbstractProductA {
return new ProductA1();
}
createProductB(param?: any) : AbstractProductB {
return new ProductB1();
}
}
export class ConcreteFactory2 implements AbstractFactory {
createProductA(param?: any) : AbstractProductA {
return new ProductA2();
}
createProductB(param?: any) : AbstractProductB {
return new ProductB2();
}
}
export class Tester {
private abstractProductA: AbstractProductA;
private abstractProductB: AbstractProductB;
constructor(factory: AbstractFactory) {
this.abstractProductA = factory.createProductA();
this.abstractProductB = factory.createProductB();
}
public test(): void {
console.log(this.abstractProductA.methodA());
console.log(this.abstractProductB.methodB());
}
}
}
核心:現在有四個商品,分別是A1、B1、A2、B2。A和B屬于兩種不同的商品緯度,而1、2則屬于商品等級。則核心就是A和B都是抽象產品角色,而創造出的A1、B1、A2、B2則是具體產品角色,而獲得具體產品的方法ConcreteFactory1
、ConcreteFactory2
,就是具體工廠角色,而他們都實現了AbstractFactory
這個抽象工廠。而最終的使用者Tester不用關心他到底是等級1還是等級2,直接使用傳入的具體工廠調用方法即可。
工廠方法模式
namespace FactoryMethodPattern {
export interface AbstractProduct {
method(param?: any) : void;
}
export class ConcreteProductA implements AbstractProduct {
method = (param?: any) => {
return "Method of ConcreteProductA";
}
}
export class ConcreteProductB implements AbstractProduct {
method = (param?: any) => {
return "Method of ConcreteProductB";
}
}
export namespace ProductFactory {
export function createProduct(type: string) : AbstractProduct {
if (type === "A") {
return new ConcreteProductA();
} else if (type === "B") {
return new ConcreteProductB();
}
return null;
}
}
}
核心:
抽象產品: AbstractProduct、具體產品: ConcreteProductA、ConcreteProductB,產品工廠:ProductFactory。 通過傳入想要生產的產品類型,得到想要的產品。客戶端使用簡單,但是缺點是隨時產品的不斷增多,會不停的增加if else邏輯,不過在ts里完全可以通過map來屏蔽這個問題。
建筑者模式
namespace BuilderPattern {
export class UserBuilder {
private name: string;
private age: number;
private phone: string;
private address: string;
constructor(name: string) {
this.name = name;
}
get Name() {
return this.name;
}
setAge(value: number): UserBuilder {
this.age = value;
return this;
}
get Age() {
return this.age;
}
setPhone(value: string): UserBuilder {
this.phone = value;
return this;
}
get Phone() {
return this.phone;
}
setAddress(value: string): UserBuilder {
this.address = value;
return this;
}
get Address() {
return this.address;
}
build(): User {
return new User(this);
}
}
export class User {
private name: string;
private age: number;
private phone: string;
private address: string;
constructor(builder: UserBuilder) {
this.name = builder.Name;
this.age = builder.Age;
this.phone = builder.Phone;
this.address = builder.Address
}
get Name() {
return this.name;
}
get Age() {
return this.age;
}
get Phone() {
return this.phone;
}
get Address() {
return this.address;
}
}
}
核心:主要解決管道式構建的問題,Builder每次只能接收一個值,之后可能才能獲取到另一個值,最終才能創造出產品。
舉例:
(async () => {
const ub = new UserBuilder('Jack');
const user = ub.setAge(await getAge(ub.getName)).setPhone('xxx').setAddress('xxx').build();
})()
原型模式
這一個設計模式有點不太懂源碼想表達的是什么。
但通常原型模式是為了解決new一個對象所損耗的資源太大,比如:
class A {
private a1: string = '';
private a2: string = '';
}
class User {
private user = {};
constructor(a: A, b, c, d, e, f, g, h, i) {
/**
* xxx....
*/
}
}
這個時候new必須傳n個參數,并且參數可能會進行復雜運算,這個時候User就該繼承一個接口Cloneable,當我們想要創建的時候不必去new一個對象,而是直接clone:
class A {
private a1: string = '';
private a2: string = '';
}
export interface Cloneable<T> {
clone(): T;
}
class User implements Cloneable<User> {
private info: {
a: A, b, c, d, e, f, g, h, I
};
constructor(a: A, b, c, d, e, f, g, h, i) {
/**
* xxx....
*/
this.info = {
a, b, c, d, e, f, g, h, I
}
}
clone(): User {
const { a, b, c, d, e, f, g, h, i } = this.info;
const newUser = new User(a, b, c, d, e, f, g, h, i);
return newUser;
}
}
需要注意的點是這里實現的是淺拷貝,由于a的類型是A,他也是一個對象,所以這樣clone出來的newUser,如果你修改了A的值newUser.a.a1 = 2
,oldUser的A的值也會發生變化為2。所以想要深拷貝還得繼續改造這個clone方法。
原型模式的優點:
- 簡化對象的創建過程,通過復制一個已有對象實例可以提高新實例的創建效率
- 擴展性好
- 提供了簡化的創建結構,原型模式中的產品的復制是通過封裝在原型類中的克隆方法實現的,無需專門的工廠類來創建產品
原型模式的缺點:
- 需要為每一個類準備一個克隆方法,而且該克隆方法位于一個類的內部,當對已有類進行改造時,需要修改原代碼,違背了開閉原則。
七種結構型模式
適配器模式
namespace AdapterPattern {
export class Adaptee {
public method(): void {
console.log("`method` of Adaptee is being called");
}
}
export interface Target {
call(): void;
}
export class Adapter implements Target {
public call(): void {
console.log("Adapter's `call` method is being called");
var adaptee: Adaptee = new Adaptee();
adaptee.method();
}
}
}
核心:將一個類的接口變換成客戶端所期待的另一種接口,從而使原本因接口不匹配而無法在一起工作的兩個類能夠一起工作。
- 源對象:
Adaptee
- 目標對象:
Target
- 適配對象:
Adapter
具體使用場景:
class ConcreteTagert implements AdapterPattern.Target {
call() {
const adapter = new AdapterPattern.Adapter();
adapter.call();
}
}
const target = new ConcreteTagert();
target.call();
或者直接用adapter替換target。
橋接模式
namespace BridgePattern {
export class Abstraction {
implementor: Implementor;
constructor(imp: Implementor) {
this.implementor = imp;
}
public callIt(s: String): void {
throw new Error("This method is abstract!");
}
}
export class RefinedAbstractionA extends Abstraction {
constructor(imp: Implementor) {
super(imp);
}
public callIt(s: String): void {
console.log("This is RefinedAbstractionA");
this.implementor.callee(s);
}
}
export class RefinedAbstractionB extends Abstraction {
constructor(imp: Implementor) {
super(imp);
}
public callIt(s: String): void {
console.log("This is RefinedAbstractionB");
this.implementor.callee(s);
}
}
export interface Implementor {
callee(s: any): void;
}
export class ConcreteImplementorA implements Implementor {
public callee(s: any) : void {
console.log("`callee` of ConcreteImplementorA is being called.");
console.log(s);
}
}
export class ConcreteImplementorB implements Implementor {
public callee(s: any) : void {
console.log("`callee` of ConcreteImplementorB is being called.");
console.log(s);
}
}
}
主要解決問題:將抽象部分與它的實現部分分離,使它們都可以獨立地變化。
核心:
- 抽象類
Abstraction
: 可以進行橋接的產品抽象,這里以apple watch類比。 - 修成抽象類
RefinedAbstractionA
:抽象類的子類,定義了具體產品,例如apple watch的的商務版、運動版、定制版等。 - 實現化角色
Implementor
:可以被橋接的產品抽象,定義了橋接的接口。類比apple watch的表帶,那么具體的接口,就可以看作是表帶的連接口。 - 具體實現化角色
ConcreteImplementorA
:可以被橋接的具體產品。比如紅色塑料表帶,金屬表帶等。
這樣任意類型的apple watch就可以和任意類型的表帶進行組合,成為新的形態或者完成新的功能。
組合模式
namespace CompositePattern {
export interface Component {
operation(): void;
}
export class Composite implements Component {
private list: Component[];
private s: String;
constructor(s: String) {
this.list = [];
this.s = s;
}
public operation(): void {
console.log("`operation of `", this.s)
for (var i = 0; i < this.list.length; i += 1) {
this.list[i].operation();
}
}
public add(c: Component): void {
this.list.push(c);
}
public remove(i: number): void {
if (this.list.length <= i) {
throw new Error("index out of bound!");
}
this.list.splice(i, 1);
}
}
export class Leaf implements Component {
private s: String;
constructor(s: String) {
this.s = s;
}
public operation(): void {
console.log("`operation` of Leaf", this.s, " is called.");
}
}
}
主要表示:部分-整體的層次結構。
核心:
-
Component
:是組合中的對象聲明接口,在適當的情況下,實現所有類共有接口的默認行為。聲明一個接口用于訪問和管理Component子部件。 -
Leaf
: 在組合中表示葉子結點對象,葉子結點沒有子結點。 -
Composite
:定義有枝節點行為,用來存儲子部件,在Component接口中實現與子部件有關操作,如增加(add)和刪除(remove)等。
裝飾者模式
裝飾者模式隱含的是通過一條條裝飾鏈去實現具體對象,每一條裝飾鏈都始于一個Componet對象,每個裝飾者對象后面緊跟著另一個裝飾者對象,而對象鏈終于ConcreteComponet對象。
namespace DecoratorPattern {
export interface Component {
operation(): void;
}
export class ConcreteComponent implements Component {
private s: String;
constructor(s: String) {
this.s = s;
}
public operation(): void {
console.log("`operation` of ConcreteComponent", this.s, " is being called!");
}
}
export class Decorator implements Component {
private component: Component;
private id: Number;
constructor(id: Number, component: Component) {
this.id = id;
this.component = component;
}
public get Id(): Number {
return this.id;
}
public operation(): void {
console.log("`operation` of Decorator", this.id, " is being called!");
this.component.operation();
}
}
export class ConcreteDecorator extends Decorator {
constructor(id: Number, component: Component) {
super(id, component);
}
public operation(): void {
super.operation();
console.log("`operation` of ConcreteDecorator", this.Id, " is being called!");
}
}
}
核心:
-
抽象組件
:給出一個抽象接口,以規范所有實現對象。 -
具體組建
:實現了抽象畫組件接口。 -
抽象裝飾
:持有一個組件,并實現抽象組件的接口。 -
具體裝飾
:負責給組件對象添加上附加的功能。
應用:
外觀模式
namespace FacadePattern {
export class Part1 {
public method1(): void {
console.log("`method1` of Part1");
}
}
export class Part2 {
public method2(): void {
console.log("`method2` of Part2");
}
}
export class Part3 {
public method3(): void {
console.log("`method3` of Part3");
}
}
export class Facade {
private part1: Part1 = new Part1();
private part2: Part2 = new Part2();
private part3: Part3 = new Part3();
public operation1(): void {
console.log("`operation1` is called ===");
this.part1.method1();
this.part2.method2();
console.log("==========================");
}
public operation2(): void {
console.log("`operation2` is called ===");
this.part1.method1();
this.part3.method3();
console.log("==========================");
}
}
}
核心:主要是解決為一組復雜的接口提供一個簡單的門面。
比如用戶下單操作,實際上我們首先需要調用用戶系統的驗證接口,其次要調用商品系統進行獲價,最后再調用訂單系統進行下單,同時還需要調用日志系統進行日志記錄。 進行外觀模式的架構后,我們只需要提供一個下單接口即可,剩下的細節用戶并不需要關心。
享元模式
namespace FlyweightPattern {
export interface Flyweight {
operation(s: String): void;
}
export class ConcreteFlyweight implements Flyweight {
private instrinsicState: String;
constructor(instrinsicState: String) {
this.instrinsicState = instrinsicState;
}
public operation(s: String): void {
console.log("`operation` of ConcreteFlyweight", s, " is being called!");
}
}
export class UnsharedConcreteFlyweight implements Flyweight {
private allState: number;
constructor(allState: number) {
this.allState = allState;
}
public operation(s: String): void {
console.log("`operation` of UnsharedConcreteFlyweight", s, " is being called!");
}
}
export class FlyweightFactory {
private fliesMap: { [s: string]: Flyweight; } = <any>{};
constructor() { }
public getFlyweight(key: string): Flyweight {
if (this.fliesMap[key] === undefined || null) {
this.fliesMap[key] = new ConcreteFlyweight(key);
}
return this.fliesMap[key];
}
}
}
運用共享技術有效地支持大量細粒度的對象。
適用性:
- 一個應用程序使用了大量的對象。
- 完全由于使用大量的對象,造成很大的存儲開銷。
- 對象的大多數狀態都可變為外部狀態。
- 如果刪除對象的外部狀態,那么可以用相對較少的共享對象取代很多組對象。
- 應用程序不依賴于對象標識。由于Flyweight對象可以被共享,對于概念上明顯有別的對象,標識測試將返回真值。
滿足以上的這些條件的系統可以使用享元對象。
核心:一個具體的場景需要很多單元(享元),并且有非常多個場景,沒個單元都有自己的固有屬性,那么在組成這非常多個場景的時候,就能復用這些已經創建好的有估計屬性的單元。
比如:關系好的朋友一起合租,在廚房公用的場景下,廚房用具就是一個個單元。合租的每一組人就是一個場景,而鍋碗瓢盆不需要每一組人都買一個,如果沒有,那么買一個大家有人買了其他一起共用即可。
代理模式
namespace ProxyPattern {
export interface Subject {
doAction(): void;
}
export class Proxy implements Subject {
private realSubject: RealSubject;
private s: string;
constructor(s: string) {
this.s = s;
}
public doAction(): void {
console.log("`doAction` of Proxy(", this.s, ")");
if (this.realSubject === null || this.realSubject === undefined) {
console.log("creating a new RealSubject.");
this.realSubject = new RealSubject(this.s);
}
this.realSubject.doAction();
}
}
export class RealSubject implements Subject {
private s: string;
constructor(s: string) {
this.s = s;
}
public doAction(): void {
console.log("`doAction` of RealSubject", this.s, "is being called!");
}
}
}
為其他對象提供一種代理以控制對這個對象的訪問。
代理對象可以在客戶端和目標對象之間起到中介的作用,這樣起到了中介的作用和保護了目標對象的作用。
客戶端不需要知道真正的目標對象,目標對象也可以隨時進行替換。