flyweightstructural.cs

来自「使用C#程序将23个常用设计模式进行列表显示」· CS 代码 · 共 80 行

CS
80
字号
using System;
using System.Windows.Forms;
using System.Collections;

namespace DesignPattern.FlyweightStructural
{
    class FlyweightStructural : AbstractPattern
    {
        public static void Run(TextBox tbInfo)
        {
            s_tbInfo = tbInfo;
            s_tbInfo.Text = "";

            // Arbitrary extrinsic state
            int extrinsicstate = 22; 
            
            FlyweightFactory f = new FlyweightFactory(); 

            // Work with different flyweight instances 
            Flyweight fx = f.GetFlyweight("X"); 
            fx.Operation(--extrinsicstate); 
            
            Flyweight fy = f.GetFlyweight("Y"); 
            fy.Operation(--extrinsicstate); 
            
            Flyweight fz = f.GetFlyweight("Z"); 
            fz.Operation(--extrinsicstate); 
            
            UnsharedConcreteFlyweight fu = new UnsharedConcreteFlyweight(); 
            fu.Operation(--extrinsicstate); 
            
            // Wait for user 
            //Console.Read();
        }
    }
    
    // "FlyweightFactory" 
    class FlyweightFactory 
    {
        private Hashtable flyweights = new Hashtable(); 
        
        // Constructor 
        public FlyweightFactory() 
        {
            flyweights.Add("X", new ConcreteFlyweight()); 
            flyweights.Add("Y", new ConcreteFlyweight());
            flyweights.Add("Z", new ConcreteFlyweight());
        } 
        
        public Flyweight GetFlyweight(string key) 
        {
            return ((Flyweight)flyweights[key]); 
        }
    } 

    // "Flyweight" 
    abstract class Flyweight 
    {
        public abstract void Operation(int extrinsicstate); 
    }
    
    // "ConcreteFlyweight" 
    class ConcreteFlyweight : Flyweight 
    {
        public override void Operation(int extrinsicstate) 
        { 
            DesignPattern.FormMain.OutputInfo("ConcreteFlyweight: " + extrinsicstate); 
        }
    }
    
    // "UnsharedConcreteFlyweight" 
    class UnsharedConcreteFlyweight : Flyweight 
    {
        public override void Operation(int extrinsicstate) 
        {
            DesignPattern.FormMain.OutputInfo("UnsharedConcreteFlyweight: " + extrinsicstate); 
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?