Interface-oriented programming is to extract a function of an object as an interface, and the specific implementation of the function is inherited from the implementation of the interface class processing.
The advantage of interface-oriented is to reduce the coupling of the program, when there are new features only need to write new features, do not need to modify the existing code
The following is a simple example:
1 //Parent Class2 Public classDuck3 {4 protectedIflybehaviour Flybehaviour;5 //an implementation that can dynamically modify a feature of an object6 Public voidsetduckfly (iflybehaviour FB)7 {8Flybehaviour =FB;9 }Ten Public voidduckfly () One { A flybehaviour.fly (); - } - } the - //Duckling class, Inherit Duck class - Public classLittleduck:duck - { + PublicLittleduck () - { +Flybehaviour =Newslowfly (); A } at } - - //big Duck class, Inherit duck class - Public classBigduck:duck - { - PublicBigduck () in { -Flybehaviour =Newquickfly (); to } + } - the //The fly behavior interface, only defines the method of flight and not implemented * Public InterfaceIflybehaviour $ {Panax Notoginseng voidFly (); - } the + //A fast-flying behavior class that inherits the flight interface A Public classQuickfly:iflybehaviour the { + Public voidFly () - { $Console.WriteLine ("very fast flying speed"); $ } - } - the //The behavior class that implements the slow flight, inherits the flight interface - Public classSlowfly:iflybehaviourWuyi { the Public voidFly () - { WuConsole.WriteLine ("very slow flight speed"); - } About}
Assuming that the duck class as a parent class duck has the ability to fly, inherit from its two sub-class big duck Bigduck fly fast, the duckling Littleduck fly slowly, through the interface-oriented approach, and through the parent class Duck Setduckfly () method, We can also dynamically modify a function during the program's operation.
Perform:
1 New Bigduck (); 2 bigduck.duckfly (); 3 4 New Littleduck (); 5 littleduck.duckfly (); 6 7 littleduck.setduckfly (new quickfly ()); 8 littleduck.duckfly ();
Results:
1 very fast flying speed 2 very slow flight speed 3 very fast flight speed
C # interface-oriented programming