首页 > 其他分享 >享元模式

享元模式

时间:2023-06-03 21:47:16浏览次数:40  
标签:享元 ConcreteFlyweight object 模式 objects flyweight interface public

The Flyweight design pattern uses sharing to support large numbers of fine-gained objects efficiently.

享元模式用共享有效支持大量细粒度的对象。

UML Class Diagram

 Flyweight: The flyweight interface enables sharing but it does not enforce it. The concrete objects which implement this interface either be shared or unshared. This is going to be an interface that defines the members of the flyweight objects.

ConcreteFlyweight: The ConcreteFlyweight class which implements the Flyweight interface, adds storage for the instrinsic state. it must be shareable and any state we are going to be store in this object should be in an instrinsic state.

FlyweightFactory: The FlyweightFactory has the GetFlyweight method and you have to pass the key to this method.It will check based on the key, whether the flyweight object is there in the cache or not. if it is there it will return that existing flyweight object, And if it is not there, then it will create a new flyweight object and add that object to the cache and return that flyweight object.

Structure code in C#

 public class FlyweightFactory
    {
        //The following dictionary is going to act as out Cache memory.
        private Dictionary<string, IFlyweight> flyweights = new Dictionary<string, IFlyweight>();

        public FlyweightFactory() 
        {
            flyweights.Add("X", new ConcreteFlyweight());
            flyweights.Add("Y", new ConcreteFlyweight());
            flyweights.Add("Z", new ConcreteFlyweight());
        }

        public IFlyweight GetFlyweight(string key)
        {
            return ((IFlyweight)flyweights[key]);
        }
    }
FlyweightFactory
 /// <summary>
    /// Flyweight interace
    /// This is an interface that defines the members of the flyweight objects
    /// </summary>
    public interface IFlyweight
    {
        void Operation(int extrinsicState);
    }

    public class ConcreteFlyweight : IFlyweight
    {
        public void Operation(int extrinsicState)
        {
            Console.WriteLine($"ConcreteFlyweight: {extrinsicState}.");
        }
    }

    public class UnsharedConcreteFlyweight : IFlyweight
    {
        public void Operation(int extrinsicState)
        {
            Console.WriteLine($"UnsharedConcreteFlyweight; {extrinsicState}.");
        }
    }
Flyweight

When to use Flyweight Design Pattern in Real-Time application?

  • Many similar objects are used and the storage coast is high.
  • The majority of each object's state data can be made extrinsic.
  • A few shared objects would easily replace many unshared objects.
  • The identity of each object does not matter

标签:享元,ConcreteFlyweight,object,模式,objects,flyweight,interface,public
From: https://www.cnblogs.com/qindy/p/17414283.html

相关文章

  • 责任链模式
    TheChainofResponsibilitydesignpatternavoidscouplingthesenderoftherequesttoitsreceiverbygivingmorethanoneobjectachancetohandletherequest.Thispatternchainsthereceivingobjectsandpassestherequestalongthechainuntilano......
  • 命令模式
    TheCommanddesignpatternencapsulatesarequestasanobject,therebylettingyouparamizeclientswithdifferentrequests,queueorlogrequests,andsupportundoableoperations.命令模式封装请求作为一个对象,因此让你参数化客户端用不同的requests,队列或者日志r......
  • 解释器模式
    Givealanguage,theInterpreterdesignpatterndefinesarepresentationforitsgrammaralongwithaninterpreterthatusestherepresentationtointerpretsentencesinthelanguage.TheInterpreterDesignPatternprovidesawaytoevaluatelanguagegram......
  • 组合模式
    TheCompositedesignpatterncomposesobjectsintotreestructurestorepresentpart-wholehierarchies.Thispatternletsclientstreatindividualobjectandcompositionsofobjectsuniformly.组合模式将对象组合成tree结构代表部分-整体层次结构,这种模式允许客户......
  • 装饰器模式
    TheDecoratorDesignPatternattachesadditionalresponsibilitiestoanobjectdynamically.Thispatternprovideaflexiblealternativetosubclassingforextendingfunctionality.装饰器模式动态的给Object添加额外的职责,这个模式为SubClassing提供灵活的扩展功能。......
  • 外观模式
    TheFacade designpattenprovidesaunifiedinterfacetoasetofinterfacesinasubsystem.Thispatterndefinesahigher-levelinterfacethatmakesthesubsystemeasiertouse.外观模式为子系统一组接口提供了统一的接口,这种模式定义了高级接口,便于子系统调用。......
  • 适配器模式
    TheAdpativedesignpatternconvertstheinterfaceofaclasstoanotherinterfaceclientsexpect.Thisdesignpatternletsclassesworktogetherthatcouldn'totherwisebecauseofincompatibleinterfaces.适配器模式将类的接口转换为客户期望的另外一个接口,这种......
  • 桥接模式
    TheBridgedesignpatterndecouplesanabstractionfromitsimplementationsothathetwocanvaryindependently.桥接模式将抽象和实现解耦,以便两者可以独立变化。UMLClassDiagram Abstraction:definestheabstraction'sinterface;matainsareferencetoanobj......
  • 模板方法模式
    TheTemplateMethoddesignpatterndefinestheskeletonofanalgorithminanoperation,deferingsomestepstosubclasses.Thispatternletssubclassesredefinecertainstepsofanalgorithmwihoutchangingthealgorithm'sstructure.模板方法设计模式在操作中......
  • 创建型设计模式
    TheCreationalDesignPatternareCategorizedintotwotypes. Object-CreationalPatterns:Object-CreationalPatternsdealwithobjectcreation.Here,itdeferspartofitsobjectcreationtoanotherobject.Class-CreationalPatterns:Class-CreationalPa......