Design pattern are abstract and hard to explain in words. But code seems simple
Visitor -- IAccept IVisitor
public interface IVisitor { Visit(Stock s);Visit(Option o);}
public interface IAccpet { void Accept(IVisitor v);}
public class Option : IAccpet {
public void Accept(IVisitor v) { v.Visit(this);}
}
public class Stock : IAccpet {
public void Accept(IVisitor v) {v.Visit(this); }
}
public class PnLVisitor : IVisitor {
void Visit(Option o) { } void Visit(Stock s) { } }
public class Trader
{
List<IAccpet> _holdings = new List<IAccpet>() { new Stock(), new Option() };
void CalcPnl() { foreach (var h in _holdings) h.Accept(new PnLVisitor()); }
}
Decorator---avoid sub-classing by composition/Wrapper
// eg. BufferStream(NetwokStream) since NS no buf
abstract class BaseComponent { }
class Decorator
{
protected BaseComponent _base;
// need to pass in concrete one
public Decorator(BaseComponent b){_base = b;}
}
Strategy --extend not modify
// new Strat extend for the same ctx
// avoid switch statement, call svc varying strat
public interface IStrategy { double Calculate();}
public class OptoinStrategy : IStrategy {
public OptoinStrategy(Context ctx) {}
public double Calculate(){return strategyValue;}
}
public class Context { }
public class Service {
IStrategy _strat;
public Service(IStrategy strat){ _strat = strat;}
public double Calc(){return _strat.Calculate();}
}
Wednesday, March 30, 2016
Think Design Pattern in psuedo-code
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment