Skip to content

Instantly share code, notes, and snippets.

@ErikZhou
Created August 7, 2013 11:28
Show Gist options
  • Select an option

  • Save ErikZhou/6173252 to your computer and use it in GitHub Desktop.

Select an option

Save ErikZhou/6173252 to your computer and use it in GitHub Desktop.
Structural Patterns - Flyweight
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