template ModeProblem Scenario
Coffee and tea are derived from abstract drinks, coffee and tea have the method of boiling water, so you can boil water to extract the method to the abstract beverage to achieve, and coffee with a coffee powder to the cup method, the tea set has a way to add tea to the cup, it looks like two methods are different logic, Abstract classes are referenced in many places by other types, that is, other types call abstract classes instead of their subclasses in order to decouple dependencies. Therefore, we should try to look different, but there are similarities in the behavior extracted into the abstract class defined as abstract members, abstract members like templates, templates always rely on subclasses to help abstract class to populate the implementation, so that at run time, invoke abstract instance can get these concrete implementation.
Summary Mode
The generalization of members that appear to have different logic but with the same behavior pattern is defined as abstract members in the abstract class, which unifies the naming of the algorithm, and the implementation is given to the subclasses to complete, thus making the reference to the abstraction more reasonable and making the decoupling and invocation more possible.
Sample CodePublic class coffe
{
//Water heaters
Public void boilwater( ) { }
//Brew coffee
Public void Brewingcoffe( ) { }
//Pour into a water cup
Public void incup( ) { }
//Add milk
Public void milkincup( ) { }
}
Public class Tea
{
//Water heaters
Public void boilwater( ) { }
//Brew tea
Public void brewingtea( ) { }
//Pour into a water cup
Public void incup( ) { }
//Add lemon
Public void lemoincup( ) { }
}
Two classes, there are boiling water and pour into the cup method, should be extracted into the abstract class defined as an instance method
Public class Drink
{
//Water heaters
Public void boilwater( ) { }
//Pour into a water cup
Public void incup( ) { }
}
Of the two classes, the object of the brew and the attached material are different, but they can be found in common, that is, the brewing and attaching materials, although the specific implementation of the details are different, but can be generalized to two the same behavior.
Public abstract class Drink
{
//Water heaters
Public void boilwater( ) { }
//Pour into a water cup
Public void incup( ) { }
//Brew, abstract
Public abstract void brewing( );
//plus materials, abstract
Public abstract void xxincup( );
}
Public class coffe : Drink
{
Public override void brewing( ) { }
Public override void xxincup( ) { c17>}
}
Public class Tea : Drink
{
Public override void brewing( ) { }
Public override void xxincup( ) { c17>}
}
C #-Design pattern Catalog
C #-Design pattern-template mode