首页 > 其他分享 >typescript: Flyweight Pattern

typescript: Flyweight Pattern

时间:2023-10-10 13:35:05浏览次数:42  
标签:sharedState typescript flyweights string Pattern param state Flyweight

 

/**
 * Flyweight Pattern 享元是一种结构型设计模式, 它允许你在消耗少量内存的情况下支持大量对象。
 * https://refactoringguru.cn/design-patterns/flyweight/typescript/example#lang-features
 * The Flyweight stores a common portion of the state (also called intrinsic
 * state) that belongs to multiple real business entities. The Flyweight accepts
 * the rest of the state (extrinsic state, unique for each entity) via its
 * method parameters.
 */


class Flyweight {

    /**
     * 
     */
    private sharedState: any;
    
    /**
     * 
     * @param sharedState 
     */
    constructor(sharedState: any) {
        this.sharedState = sharedState;
    }
    /**
     * 
     * @param uniqueState 
     */
    public operation(uniqueState):string {  //void
        let str="";
        const s = JSON.stringify(this.sharedState);
        const u = JSON.stringify(uniqueState);
        console.log(`Flyweight: Displaying shared (${s}) and unique (${u}) state.`);
        str=str+s+","+u;
        return str;
    }
}

/**
 * The Flyweight Factory creates and manages the Flyweight objects. It ensures
 * that flyweights are shared correctly. When the client requests a flyweight,
 * the factory either returns an existing instance or creates a new one, if it
 * doesn't exist yet.
 */
class FlyweightFactory {
    /**
     * 
     */
    private flyweights: {[key: string]: Flyweight} = <any>{};

    /**
     * 
     * @param initialFlyweights 
     */
    constructor(initialFlyweights: string[][]) {
        for (const state of initialFlyweights) {
            this.flyweights[this.getKey(state)] = new Flyweight(state);
        }
    }

    /**
     * Returns a Flyweight's string hash for a given state.
     */
    private getKey(state: string[]): string {
        return state.join('_');
    }

    /**
     * Returns an existing Flyweight with a given state or creates a new one.
     */
    public getFlyweight(sharedState: string[]): Flyweight {
        const key = this.getKey(sharedState);

        if (!(key in this.flyweights)) {
            console.log('FlyweightFactory: Can\'t find a flyweight, creating new one.');
            this.flyweights[key] = new Flyweight(sharedState);
        } else {
            console.log('FlyweightFactory: Reusing existing flyweight.');
        }

        return this.flyweights[key];
    }
    /**
     * 
     */
    public listFlyweights():string { //void
        let str="";
        const count = Object.keys(this.flyweights).length;
        console.log(`\nFlyweightFactory: I have ${count} flyweights:`);
        for (const key in this.flyweights) {
            console.log(key);
            str=str+","+key;
        }

        return str;
    }
}

/**
 * The client code usually creates a bunch of pre-populated flyweights in the
 * initialization stage of the application.
 */
const factory = new FlyweightFactory([
    ['Chevrolet', 'Camaro2018', 'pink'],
    ['Mercedes Benz', 'C300', 'black'],
    ['Mercedes Benz', 'C500', 'red'],
    ['BMW', 'M5', 'red'],
    ['BMW', 'X6', 'white'],
    // ...
]);
let pubf1="";
let pubf2="";
let pubf3="";
let pubf4="";

pubf3=factory.listFlyweights();

// ...
/**
 * 
 * @param ff 
 * @param plates 
 * @param owner 
 * @param brand 
 * @param model 
 * @param color 
 */
function addCarToPoliceDatabase(
    ff: FlyweightFactory, plates: string, owner: string,
    brand: string, model: string, color: string,
) {
    console.log('\nClient: Adding a car to database.');
    const flyweight = ff.getFlyweight([brand, model, color]);

    // The client code either stores or calculates extrinsic state and passes it
    // to the flyweight's methods.
   return flyweight.operation([plates, owner]);


}

pubf1=addCarToPoliceDatabase(factory, 'CL234IR', 'James Doe', 'BMW', 'M5', 'red');

pubf2=addCarToPoliceDatabase(factory, 'CL234IR', 'James Doe', 'BMW', 'X1', 'red');

pubf4=factory.listFlyweights();



let messageflyweight: string = 'Hello World,This is a typescript!,涂聚文 Geovin Du.Web';
document.body.innerHTML = messageflyweight+",<br/>one="+pubf1+",<br/>two="+pubf2+",<br/>thee="+pubf3+",<br/>four="+pubf4+",<br/>TypeScript Flyweight Pattern 享元模式";

  

调用:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <head><title>TypeScript Hello Flyweight Pattern 享元模式</title>
      <meta name="Description" content="geovindu,涂聚文,Geovin Du"/>
<meta name="Keywords" content="geovindu,涂聚文,Geovin Du"/>
<meta name="author" content="geovindu,涂聚文,Geovin Du"/> 
    </head>
    <body>
        <script src="dist/Flyweightts.js"></script>
    </body>
</html>

  

 

输出:

 

标签:sharedState,typescript,flyweights,string,Pattern,param,state,Flyweight
From: https://www.cnblogs.com/geovindu/p/17754438.html

相关文章

  • 设计模式之 Observer Pattern观察者模式
    观察者模式Observer  Observer模式为组件向相关接收方【广播】消息提供了灵活的方法;  该模式定义了对象一到多的依赖关系,这样当对象改变状态时,将自动通知并更新他所有的依赖对象;  优点    抽象了主体与Observer之间的耦合关系;    支持广播方式的通信......
  • 【愚公系列】2023年10月 二十三种设计模式(八)-组合模式(Composite Pattern)
    ......
  • TypeScript与JavaScript比较(区别)
     TypeScript和JavaScript是目前项目开发中较为流行的两种脚本语言,TypeScript是JavaScript的一个超集,但是TypeScript与JavaScript之间又有什么样的区别呢?在选择开发语言时,又该如何抉择呢?本文将会深入对比这两种语言,讨论两种语言之间的关联和差异,并概述两种语言各自的优势......
  • TypeScript基础
    基础类型:":"后面为变量的数据类型布尔值:booleanletisDone:boolean=false数字:numberTypeScript中的所有数字类型都是浮点数,类型统一都是number,支持十进制,二进制,八进制,十六进制。letcount:number=100字符串:stringTypescript中使用string表示文本数据类型,可以使用双引......
  • 【愚公系列】2023年10月 二十三种设计模式(七)-桥接模式(Bridge Pattern)
    ......
  • 设计模式之 State Pattern状态模式
    State模式允许对象在内部状态变化时,变更其行为,并修改其类;优点:定位指定状态的行为,并且针对不同状态来划分行为,使状态转换显式进行;适用:对象的行为依赖于其状态,并且该对象必须在运行时根据其状态修改其行为;操作具有大量的以及多部分组成的取决于对象状态的条件语句; publicc......
  • typescript: Facade Pattern
     /***Facadepattern外观是一种结构型设计模式,能为复杂系统、程序库或框架提供一个简单(但有限)的接口。*TheFacadeclassprovidesasimpleinterfacetothecomplexlogicofoneor*severalsubsystems.TheFacadedelegatestheclientrequeststothe*......
  • TypeScript入门到精通——TypeScript类型系统基础——元组类型
    TypeScript类型系统基础——元组类型 元组(Tuple)表示由有限元素构成的有序列表。在JavaScript中,没有提供原生的元组数据类型。TypeScript对此进行了补充,提供了元组数据类型。由于元组数组之间存在很多共性,因此TypeScript使用数组来表示元组。 在TypeScript中,元组类型......
  • TypeScript入门到精通——TypeScript类型系统基础——数组类型
    数组类型 数组是十分常用的数据结构,它表示一组有序元素的集合。在TypeScript中,数组值的数据类型为数组类型。一、数组类型定义 TypeScript提供了以下两种方式来定义数组类型:简单数组类型表示法泛型数组类型表示法1.1、简单数组类型表示法在TypeScript中,你可以使......
  • 【愚公系列】2023年10月 二十三种设计模式(五)-单例模式(Singleton Pattern)
    ......