程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#設計模式之享元設計模式(Flyweight)(2)

C#設計模式之享元設計模式(Flyweight)(2)

編輯:關於C語言

三、單純享元模式的示意性源代碼

// Flyweight pattern -- Structural example 
using System;
using System.Collections;
// "FlyweightFactory"
class FlyweightFactory
{
 // FIElds
 private Hashtable flyweights = new Hashtable();
 // Constructors
 public FlyweightFactory()
 {
  flyweights.Add("X", new ConcreteFlyweight());
  flyweights.Add("Y", new ConcreteFlyweight());
  flyweights.Add("Z", new ConcreteFlyweight());
 }
 // Methods
 public Flyweight GetFlyweight(string key)
 {
  return((Flyweight)flyweights[ key ]);
 }
}
// "Flyweight"
abstract class Flyweight
{
 // Methods
 abstract public void Operation( int extrinsicstate );
}
// "ConcreteFlyweight"
class ConcreteFlyweight : Flyweight
{
 private string intrinsicstate = "A";
 // Methods
 override public void Operation( int extrinsicstate )
 {
  Console.WriteLine("ConcreteFlyweight: intrinsicstate {0}, extrinsicstate {1}",
   intrinsicstate, extrinsicstate );
 }
}
/**//// <summary>
/// ClIEnt test
/// </summary>
public class ClIEnt
{
 public static void Main( string[] args )
 {
  // Arbitrary extrisic 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 );
 }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved