标签:wcf
任务理解接口式编程,定义一个接口是为了遵循中规范,便于程序的扩展。接口是一种能力也是一种约定。1、接口不可以被实例化 2、实现类必须实现接口的所有方法(抽象类除外)3、接口可以实现多继承 4、接口中可定义属性。
打印机需要墨盒和纸张。墨盒有黑白、彩色。纸张有A4 B5.打印机怎么实现对不同纸张好墨盒打印的呢?接口契约式编程,打印机执行定义纸张接口和墨盒接口两个约定。纸张厂家和墨盒厂家只需遵循约定就可有打印。
接口契约墨盒
public interface IInkBox
    {
       string getColor();
    }纸张
public interface IPaper
    {
       string getSize();
    }遵循约定纸张厂家造纸 A4 B5两种纸张
 class A4Paper:IPaper
    {
        public stringgetSize()
        {
            return "A4Paper";
        }
    }
 
  class B5Paper:IPaper
    {
        public stringgetSize()
        {
            return "B5Paper";
        }
    }墨盒厂家遵循约定墨盒黑白 彩色
class ColorBox:IInkBox
    {
        public stringgetColor()
        {
            return "彩色";
        }
    }
 
class GrayBox:IInkBox
    {
        public stringgetColor()
        {
            return "黑白";
        }
}打印机类
  class Printer
    {
        public voidgetPrinter(IInkBox box, IPaper paper)
        {
            Console.Write("用{0}墨盒,纸张{1}",box.getColor(),paper.getSize());
        }
    }
打印机实现打印不同纸张和不同颜色的方法 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);//打印机厂商给出一个约定,纸张和墨盒厂商遵循
            Console.WriteLine();
           printer.getPrinter(colorBox,B5);
            Console.Read();
        }可以看出面向契约式编程,非常编译程序的扩展。如果又需要打印其他的纸张,执行遵循纸张接口就可以了。
标签:wcf
原文地址:http://blog.csdn.net/jielizhao/article/details/43149541