A brief introduction to WCF Programming II (Interface contract programming)
Task understanding interface programming, defining an interface is to follow the norms in order to facilitate the extension of the program. An interface is a capability and a convention. 1, the interface can not be instantiated 2, the implementation of the class must implement the interface of all methods (except the abstract class) 3, the interface can implement multiple inheritance 4, the interface can be defined properties.
Instance
The printer requires ink cartridges and paper. The cartridge has black and white color. The paper has A4 B5. How does the printer achieve a good print cartridge for different paper? Interface contract programming, the printer performs the definition of the paper interface and cartridge interface two conventions. Paper Manufacturers and ink cartridges manufacturers only need to follow the Convention can be printed.
Code
Interface Contract Cartridges
Public interface Iinkbox { string getColor (); }
Paper
Public interface Ipaper { string getsize (); }
Follow the convention paper manufacturers paper A4 B5 Two kinds of paper
Class A4paper:ipaper {public stringgetsize () { return "A4paper"; } } Class B5paper:ipaper {public stringgetsize () { return "B5paper"; } }
Ink cartridge manufacturers Follow the agreed cartridge black and white color
Class Colorbox:iinkbox {public stringgetcolor () { return "color"; } } class Graybox:i Inkbox {public stringgetcolor () { return "black and white"; }}
Printer class
Class Printer {public voidgetprinter (iinkbox box, Ipaper paper) { Console.Write ("with {0} ink cartridges, paper {1}" , Box.getcolor (), paper.getsize ()); } }
Printer implementation method for printing different paper and different colors staticvoid Main (string[]args)
{ Graybox Gray = Newgraybox (); A4paper A4 = new A4paper (); Colorbox Colorbox = Newcolorbox (); B5paper B5 = new B5paper (); Printer Printer = Newprinter (); Printer.getprinter (GRAY,A4);//printer manufacturer gives a contract, paper and ink cartridges manufacturers follow Console.WriteLine (); Printer.getprinter (COLORBOX,B5); Console.read (); }
Summarize
It can be seen that contract-oriented programming, the extension of a very compiled program. If you need to print additional paper, follow the paper interface.
WCF bis (interface-contract programming IDEA)