好记性不如烂笔头——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();


相关文章
|
Nacos 数据安全/隐私保护
springCloud之nacos服务注册与发现、配置中心
springCloud之nacos服务注册与发现、配置中心
541 0
|
算法 Java 大数据
深入理解操作系统的内存管理机制
【4月更文挑战第27天】 在现代计算机系统中,操作系统扮演着至关重要的角色,尤其是内存管理作为其核心功能之一,它直接关系到系统性能和稳定性。本文将探讨操作系统中内存管理的基本原理、关键技术以及面临的挑战,旨在为读者提供一个清晰的内存管理概念框架,并通过分析不同内存管理策略的优缺点,揭示其对操作系统整体性能的影响。
204 2
|
缓存 JavaScript
【vue】如何实现图片预加载
【vue】如何实现图片预加载
142 0
|
程序员 Python
Python Qt GUI设计:QScrollBar类实现窗口水平或垂直滑动条效果(拓展篇—4)
使用QScrollBar可以在窗口控件提供了水平的或垂直的滚动条,这样可以扩大当前窗口的有效装载面积,从而装载更多的控件。
|
人工智能 自然语言处理 机器人
Siri太笨,根本打不过ChatGPT!苹果加急测试语言生成AI
Siri太笨,根本打不过ChatGPT!苹果加急测试语言生成AI
231 0
|
运维 Prometheus Cloud Native
2022阿里云可观测技术峰会
6月22日 10:00,详细解读企业IT团队如何借助可观测能力提升运维效能,打造更优质用户体验,实现数字化转型与创新。
872 0
2022阿里云可观测技术峰会
|
iOS开发 开发者
iOS中的网络和多线程编程(十)
iOS中的网络和多线程编程(十)
248 0
iOS中的网络和多线程编程(十)
|
缓存 安全 Java
Shiro第三篇【授权过滤器、与ehcache整合、验证码、记住我】(二)
本文主要讲解的知识点有以下: Shiro授权过滤器使用 Shiro缓存 与Ehcache整合 Shiro应用->实现验证码功能 记住我功能
321 0
Shiro第三篇【授权过滤器、与ehcache整合、验证码、记住我】(二)
|
网络协议 Java 编译器
【Android Protobuf 序列化】Protobuf 服务器与客户端通信 ( TCP 通信中使用 Protobuf )
【Android Protobuf 序列化】Protobuf 服务器与客户端通信 ( TCP 通信中使用 Protobuf )
532 0
|
移动开发 NoSQL Redis
redis源码笔记 - redis-cli.c
这份代码是redis的client接口,其和server端的交互使用了deps目录下的hiredis c库,同时,在这部分代码中,应用了linenoise库完成类似history命令查询、自动补全等终端控制功能。
1135 1