Created
August 7, 2013 11:28
-
-
Save ErikZhou/6173252 to your computer and use it in GitHub Desktop.
Structural Patterns - Flyweight
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections; | |
| class MainApp | |
| { | |
| static void Main() | |
| { | |
| // 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 uf = new | |
| UnsharedConcreteFlyweight(); | |
| uf.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) | |
| { | |
| Console.WriteLine("ConcreteFlyweight: " + extrinsicstate); | |
| } | |
| } | |
| // "UnsharedConcreteFlyweight" | |
| class UnsharedConcreteFlyweight : Flyweight | |
| { | |
| public override void Operation(int extrinsicstate) | |
| { | |
| Console.WriteLine("UnsharedConcreteFlyweight: " + | |
| extrinsicstate); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment