好记性不如烂笔头——23种设计模式(上)

简介: 好记性不如烂笔头——23种设计模式(上)

使用思维导图来阐述23种设计模式,并以TypeScript实现其代码,让我们前端切图崽写出的代码具有可扩展性、可复用性、减少代码冗余问题,提升自身内功。

640.jpg

一、设计原则



640.jpg



二、创建型模式



创建型模式包含单例模式、简单工厂模式、工厂方法模式、抽象工厂模式、原型模式、建造者模式。创建型模式就是创建对象的模式,抽象了实例化的过程。它帮助一个系统独立于如何创建、组合和表示它的那些对象。关注的是对象的创建,创建型模式将创建对象的过程进行了抽象,也可以理解为将创建对象的过程进行了封装,作为客户程序仅仅需要去使用对象,而不再关心创建对象过程中的逻辑。


2.1 单例模式

640.jpg


// 饿汉式
class Singleton1 {
    // 1. 构造器私有化,外部不能new
    private constructor(){}
    // 2. 本类内部创建对象实例化
    private static instance : Singleton1 = new Singleton1();
    // 3. 提供一个公有的静态方法,返回实例对象
    public static getInstance() : Singleton1 {
        return this.instance;
    }
}
console.log(Singleton1.getInstance(), '11111');
// 懒汉式
class Singleton2 {
    private constructor(){}
    private static instance: Singleton2 = null;
    public static getInstance() : Singleton2 {
        if (this.instance === null) {
            this.instance = new Singleton2();
        }
        return this.instance;
    }
}
console.log(Singleton2.getInstance(), '2222')

2.2 简单工厂模式

640.jpg

// 抽象产品接口
interface Product{}
// 具体产品一
class ConcreteProduct1 implements Product {
    constructor(){}
}
// 具体产品二
class ConcreteProduct2 implements Product {
    constructor(){}
}
// 简单工厂
class SimpleFactory {
    public static createProduct(type : number) : Product {
        let product = null;
        if (type === 1) {
            product = new ConcreteProduct1();
        } else if ( type === 2) {
            product = new ConcreteProduct2();
        }
        return product;
    }
}
// 使用
let product = SimpleFactory.createProduct(1);
console.log(product);

2.3 工厂方法模式


640.jpg


// 抽象产品接口
interface Product2{
    method1() : void;
    method2() : void;
}
// 具体产品一
class ConcreteProduct_1 implements Product2 {
    constructor(){}
    method1() {
    }
    method2() {
    }
}
// 具体产品二
class ConcreteProduct_2 implements Product2 {
    constructor(){}
    method1() {
    }
    method2() {
    }
}
// 抽象工厂
abstract class Creator {
    public abstract createProduct(type : number) : Product;
}
// 具体工厂
class ConcreteCreator extends Creator {
    constructor(){
        super();
    }
    public createProduct(type : number) : Product {
        let product = null;
        if (type === 1) {
            product = new ConcreteProduct_1();
        } else if (type === 2) {
            product = new ConcreteProduct_2();
        }
        return product;
    }
}
// 使用
const creator : Creator = new ConcreteCreator();
const myProduct : Product = creator.createProduct(1);

2.4 抽象工厂模式

640.jpg


// 抽象工厂接口
interface AbstractFactory {
    createProductA() : AbstractProductA;
    createProductB() : AbstractProductB;
}
// 抽象产品A接口
interface AbstractProductA {}
// 抽象产品B接口
interface AbstractProductB {}
// 具体工厂1
class ConcreteFactory1 implements AbstractFactory {
    constructor() {}
    public createProductA() : AbstractProductA {
        return new ConcreteProductA1();
    }
    public createProductB() : AbstractProductB {
        return new ConcreteProductB1();
    }
}
// 具体工厂2
class ConcreteFactory2 implements AbstractFactory {
    constructor() {}
    public createProductA() : AbstractProductA {
        return new ConcreteProductA2();
    }
    public createProductB() : AbstractProductB {
        return new ConcreteProductB2();
    }
}
// 具体产品A1
class ConcreteProductA1 implements AbstractProductA {}
// 具体产品A2
class ConcreteProductA2 implements AbstractProductA {}
// 具体产品B1
class ConcreteProductB1 implements AbstractProductB {}
// 具体产品B2
class ConcreteProductB2 implements AbstractProductA {}
// 使用
const factory1 : AbstractFactory = new ConcreteFactory1();
const factory2 : AbstractFactory = new ConcreteFactory2();
const productA1 : AbstractProductA = factory1.createProductA();
const productA2 : AbstractProductA = factory2.createProductA();
const productB1 : AbstractProductB = factory1.createProductB();
const productB2 : AbstractProductB = factory2.createProductB();

2.5 原型模式

640.jpg


interface Prototype {
    clone():Prototype;
}
class Dog implements Prototype {
    public name: string;
    public birthYear: number;
    public sex: string;
    public presentYear: number;
    constructor() {
        this.name = "lili";
        this.birthYear = 2015;
        this.sex = "男";
        this.presentYear = 2018;
    }
    public getDiscription(): string {
        return `狗狗叫${this.name},性别${this.sex},${this.presentYear}年${this.presentYear - this.birthYear}岁了`
    }
    // 实现复制
    public clone(): Prototype {
        return Object.create(this);
    }
}
// 使用
const dog = new Dog();
console.log(dog.getDiscription());
dog.presentYear = 2020;
const dog1 = Object.create(dog);
console.log(dog1.getDiscription());

2.6 建造者模式


640.jpg


// 抽象建造者
abstract class Builder {
    public abstract buildPartA() : void;
    public abstract buildPartB() : void;
    public abstract buildPartC() : void;
    public abstract buildProduct() : Product;
}
// 具体建造者
class ConcreteBuilder extends Builder {
    private product : Product;
    constructor(product : Product) {
        super();
        this.product = product;
    }
    public buildPartA() : void {}
    public buildPartB() : void {}
    public buildPartC() : void {}
    // 最终组建一个产品
    public buildProduct() : Product {
        return this.product;
    }
}
// 产品角色
class Product {
    public doSomething() : void {
        // 独立业务
    }
}
// 指挥者
class Director {
    private _builder : Builder;
    constructor(builder : Builder) {
        this._builder = builder;
    }
    set builder(builder : Builder) {
        this._builder = builder;
    }
    // 将处理建造的流程交给指挥者
    public constructorProduct() {
        this._builder.buildPartA();
        this._builder.buildPartB();
        this._builder.buildPartC();
        return this._builder.buildProduct();
    }
}
// 使用
const builder : Builder = new ConcreteBuilder(new Product());
const director : Director = new Director(builder);
const product : Product = director.constructorProduct();

三、结构型模式



结构型模式包含适配器模式、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式。结构型模式为解决怎样组装现有的类,设计他们的交互方式,从而达到实现一定的功能。


3.1 适配器模式

640.jpg

// 类适配器
// 目标对象
interface Target {
    request() : void;
}
// 被适配者
class Adaptee {
    constructor() {}
    // 这是源角色,有自己的的业务逻辑
    public specificRequest() : void {}
}
// 适配器
class Adapter extends Adaptee implements Target {
    constructor() {
        super();
    }
    public request() : void {
        super.specificRequest();
    }
}
const target : Target = new Adapter();
target.request();
// 对象适配器
// 目标对象
interface Target {
    request() : void;
}
// 被适配者
class Adaptee {
    constructor() {}
    // 这是源角色,有自己的的业务逻辑
    public specificRequest() : void {}
}
// 适配器
class Adapter implements Target {
    private adaptee : Adaptee;
    constructor(adaptee : Adaptee) {
        this.adaptee = adaptee;
    }
    public request() : void {
        this.adaptee.specificRequest();
    }
}
// 使用
const target : Target = new Adapter(new Adaptee());
target.request();
// 接口适配器
interface Adaptee {
    operation1() : void;
    operation2() : void;
}
abstract class AbsAdapter implements Adaptee {
    public operation1() : void {}
    public operation2() : void {}
}
class UseClass extends AbsAdapter {
    public operation1() : void {}// 重写该类
}

3.2 桥接模式


640.jpg


// 实现接口角色
interface Implementor {
    doSomething() : void;
    doAnything() : void;
}
// 具体实现角色
class ConcreteImplementor1 implements Implementor {
    public doSomething() : void {
    }
    public doAnything() : void {
    }
}
class ConcreteImplementor2 implements Implementor {
    public doSomething() : void {
    }
    public doAnything() : void {
    }
}
// 抽象类
abstract class Abstraction {
    private imp : Implementor;
    constructor(imp : Implementor) {
        this.imp = imp;
    }
    // 自身的行为和属性
    public request() : void {
        this.imp.doSomething();
    }
}
// 具体抽象化角色
class RefinedAbstraction extends Abstraction {
    constructor(imp : Implementor) {
        super(imp);
    }
    public request() : void {
        // 自己写一些处理业务
        super.request();
    }
}
// 调用
// 定义一个实现化角色
const imp : Implementor = new ConcreteImplementor1();
// 定义一个抽象化角色
const abs : Abstraction = new RefinedAbstraction(imp);
// 执行上下文
abs.request();


3.3 装饰者模式

640.jpg


// 抽象构件
abstract class Component {
    public abstract operate() : void;
}
// 具体构件
class ConcreteComponent extends Component {
    public operate() : void {
        console.log('do something');
    }
}
// 装饰角色
abstract class Decorator extends Component {
    private component : Component = null;
    constructor(component : Component ) {
        super();
        this.component = component;
    }
    public operate() : void {
        this.component.operate();
    }
}
// 具体装饰者
class ConcreteDecoratorA extends Decorator {
    constructor(component : Component) {
        super(component);
    }
    // 定义自己的修饰方法
    private methodA() : void {
        console.log('methodA修饰');
    }
    // 重写父类方法
    public operate() : void {
        this.methodA();
        super.operate();
    }
}
class ConcreteDecoratorB extends Decorator {
    constructor(component : Component) {
        super(component);
    }
    // 定义自己的修饰方法
    private methodB() : void {
        console.log('methodB修饰');
    }
    // 重写父类方法
    public operate() : void {
        this.methodB();
        super.operate();
    }
}
function main() {
    let component : Component = new ConcreteComponent();
    // 第一次装饰
    component = new ConcreteDecoratorA(component);
    // 第二次装饰
    component = new ConcreteDecoratorB(component);
    // 装饰后运行
    component.operate();
}
main();


3.4 组合模式

640.jpg


abstract class Component {
    protected name : string;
    constructor(name : string) {
        this.name = name;
    }
    public abstract doOperation() : void;
    public add(component : Component) : void {
    }
    public remove(component : Component) : void {
    }
    public getChildren() : Array<Component> {
        return [];
    }
}
class Composite extends Component {
    // 构件容器
    private componentList : any;
    constructor(name : string) {
        super(name);
        this.componentList = [];
    }
    public doOperation() : void {
        console.log(`这是容器${this.name},处理一些逻辑业务!`);
    }
    public add(component : Component) : void {
        this.componentList.push(component);
    }
    public remove(component : Component) : void {
        const componentIndex = this.componentList.findIndex((value : Component, index : Number) => {
            return value == component;
        });
        this.componentList.splice(componentIndex, 1);
    }
    public getChildren() : Array<Component> {
        return this.componentList;
    }
}
class Leaf extends Component {
    constructor(name : string) {
        super(name);
    }
    public doOperation() : void {
        console.log(`这是叶子节点${this.name},处理一些逻辑业务!`);
    }
}
function main() {
    const root : Component  = new Composite('root');
    const node1 : Component = new Leaf('1');
    const node2 : Component = new Composite('2');
    const node3 : Component = new Leaf('3');
    root.add(node1);
    root.add(node2);
    root.add(node3);
    const node2_1 : Component = new Leaf("2_1");
    node2.add(node2_1);
    const children1 = root.getChildren();
    console.log(children1);
    root.remove(node2);
    const children2 = root.getChildren();
    console.log(children2);
}
main();


3.5 外观模式

640.jpg


class SubSystemA {
    public doOperationA() : void {
        console.log('子系统A的举动');
    }
}
class SubSystemB {
    public doOperationB() : void {
        console.log('子系统B的举动');
    }
}
class Facade {
    private subSystemA : SubSystemA;
    private subSystemB : SubSystemB;
    constructor() {
        this.subSystemA = new SubSystemA();
        this.subSystemB = new SubSystemB();
    }
    public doOperation() : void {
        this.subSystemA.doOperationA();
        this.subSystemB.doOperationB();
    }
}
function main() {
    const facade : Facade = new Facade();
    facade.doOperation();
}
main();


3.6 享元模式


640.jpg


abstract class Flyweight {
    public abstract doOperation(extrinsicState : string) : void;
}
class ConcreteFlyweight extends Flyweight {
    private intrinsicState : string;
    constructor(intrinsicState : string) {
        super();
        this.intrinsicState = intrinsicState;
    }
    public doOperation(extrinsicState : string) : void {
        console.log(`这是具体享元角色,内部状态为${this.intrinsicState},外部状态为${extrinsicState}`);
    }
}
interface flyweightObject {
    [key : string] : Flyweight
}
class FlyweightFactory {
    private flyweights : flyweightObject;
    constructor() {
        this.flyweights = {};
    }
    public getFlyweight(intrinsicState : string) : Flyweight {
        if (!this.flyweights[intrinsicState]) {
            const flyweight : Flyweight = new ConcreteFlyweight(intrinsicState);
            this.flyweights[intrinsicState] = flyweight;
        }
        return this.flyweights[intrinsicState];
    }
}
function main() {
    const factory : FlyweightFactory = new FlyweightFactory();
    const flyweight1 : Flyweight = factory.getFlyweight("aa");
    const flyweight2 : Flyweight = factory.getFlyweight("aa");
    flyweight1.doOperation('x');
    flyweight2.doOperation('y');
}
main();


相关文章
|
7天前
|
设计模式 安全 图形学
Unity精华☀️ 面试官眼中的「设计模式」
Unity精华☀️ 面试官眼中的「设计模式」
|
3月前
|
设计模式 存储 缓存
设计模式全览:编程艺术的精髓!
设计模式全览:编程艺术的精髓!
31 0
|
3月前
|
设计模式 自动驾驶 NoSQL
设计模式心法
设计模式心法
|
设计模式 数据库
几张图带你手拿把掐设计模式六大原则
几张图带你手拿把掐设计模式六大原则
60 0
|
设计模式
面试官问我什么是责任链模式,我把这篇文章甩给了他
面试官问我什么是责任链模式,我把这篇文章甩给了他
面试官问我什么是责任链模式,我把这篇文章甩给了他
|
存储 算法 Java
我该如何学好行为型模式(上)
我该如何学好行为型模式(上)
39 0
|
Java 程序员
我该如何学好行为型模式(下)
我该如何学好行为型模式(下)
55 0
设计模式肝完了,还挺全!
有的时候会问设计模式基本的概念,有的时候会问设计模式具体的内容或者让你手画图,有的时候会问框架用到了那些设计模式!
120 0
设计模式肝完了,还挺全!
|
设计模式 机器人 Java
程序员内功心法之适配器模式
程序员内功心法之适配器模式
124 0
程序员内功心法之适配器模式
|
设计模式 缓存 安全
【设计模式】从女娲娘娘到取媳妇
💫你好,我是小航,一个正在变秃、变强的准大三党 💫本文主要讲解设计模式,示例Demo采用Java语言演示 💫欢迎大家的关注!
149 0
【设计模式】从女娲娘娘到取媳妇

相关实验场景

更多