Professional Documents
Culture Documents
Design Patterns
Design Patterns
Design Patterns
Activator
public class C {
public C() { … }
}
public class C {
public static C NewC() {
return new C();
}
}
private
base() this()
class PersonFactory {
public Person MakePerson(
int age)
{
if (age < 18)
return new Minor();
else
return new Adult();
}
}
string.Format(
“<person name=\”{0}\”,
name)
XElement(“person”,
XAttribute(“name”, name))
.ToString();
StringBuilder AppendFormat()
AppendLine()
stringBuilder.AppendFormatLine(format, params)
ICloneable
Clone()
ToString() GetHashCode()
[Serializable]
public abstract class IPrototype<T>
{
public T DeepCopy()
{
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
T copy = (T)formatter.Deserialize(stream);
stream.Close();
return copy;
}
}
DeepCopy
IPrototype<T>
WeakReference
new
public class C
{
private C() { /* nothing here */ }
class CMaker {
static CMaker () { }
internal static readonly C instance = new C();
}
interface IRandom {
int RandomNumber();
}
RandomGenerator
IRandom
class RandomAdapter:
RandomGenerator, IRandom
{
int RandomNumber() {
return GetRandom().Next();
}
}
– RandomGenerator rg = new RandomGenerator();
Random r = rg.GetRandom();
class CContainer {
private Collection<C> items;
}
class Neuron
{ … }
class Layer :
Collection<Neuron>
{ … }
neuron.ConnectTo(otherNeuron);
neuron.ConnectTo(layer);
layer.ConnectTo(neuron);
layer.ConnectTo(otherLayer);
– IEnumerable<T>
yield return this;
ICollection<T>
Card CardInPlay
♣ ♠ ♥ ♦
Rank
Suit
Rank
Suit
Orientation
IA IB
A B
→
→
new
Bitmap
byte[]
Reflection.Emit
XElement.Parse
→
IEnumerable<T>
yield return
GetEnumerator()
AsyncEnumerator
→
→
interface ICarState
{
void Go(Context ctx); // Drive?
}
class Context {
ICarState state;
public void GoGoGo() {
state.Go(this);
state.Go(this); // yeah, right :)
state.Go(this);
}
}
class CrashedState : class MovingState :
ICarState ICarState
{ {
void Go(Context ctx) void Go(Context ctx)
{ {
MessageBox.Show( // driving
“Are you crazy?”); // is that a rock?
}
} // CRASH!
The state ctx.state =
just new CrashedState();
changed! }
}
interface IStrategy
{
void Evaluate(Context ctx);
}
SingleEvaluator, ParralelEvaluator,
GpuEvaluator
class Context {
IStrategy strategy;
Matrix m1, m2;
static void Multiply(Matrix m1, Matrix m2)
{ this.m1 = m1; this.m2 = m2;
if (strategy == null) { // on-demand
if (gpu.pixelShader >= 2.0)
strategy = new GpuStrategy();
else if (Environment.ProcessorCount > 1)
strategy = new ParallelStrategy();
else strategy = new SingleStrategy();
}
strategy.Evaluate(this);
}
}
→
→
StringBuilder