Duck base class to encapsulate behavior.
class Duck { protected iflybehavior flybehavior; protected iquackbehavior quackbehavior; Public void Performquack () { quackbehavior.quack (); } Public void performfly () { flybehavior.fly (); } }
Flight behavior base class
Interface Iflybehavior { void Fly (); }
Duck-ringing behavior base class
Interface Iquackbehavior { void quack (); }
Different behavior of the flight
class Flynoway:iflybehavior { publicvoid Fly () { Console.WriteLine (" Not fly "); } }
Public class Flywithwings:iflybehavior { publicvoid Fly () { Console.WriteLine (" fly " ); } }
Ducks are the same way.
Sub-class Duck
class Mallardduck:duck { public Mallardduck () { new mutequack (); New flywithwings (); } }
How the main function is called
class program { staticvoid Main (string[] args) { new Mallardduck (); Mallardduck.performfly (); Mallardduck.performquack (); Console.readkey (); } }
Headfirst design Pattern---Policy Mode C # implementation