Policy mode
Role:
A policy pattern is a method that defines a series of algorithms, all of which are done the same work, but are implemented differently, and he can invoke all the algorithms in the same way. The strategy model is easy to understand, and even if you have not studied design patterns, you can think of this pattern to solve problems in real-world problems.
Compared to the factory model:
- The function of the factory pattern is to instantiate the object , which does not contain the action of the object
- In the policy mode, it is encapsulated again, not only to instantiate the algorithm in its own class, but also to manipulate the algorithm. the client has been encapsulated again, making the client's code simpler and clearer.
Class Diagram:
Realize:
1. Form of Cashsuper algorithm
Public Abstract class Cashsuper { publicabstractdouble GetCash (double );}
View Code
2, three inherited algorithms
Public classCashrebateextendsCashsuper {Private Doublerebate = 1; PublicCashrebate (Doublerebate) { This. Rebate =Rebate; } @Override Public DoubleGetCash (DoubleMoney ) { //TODO auto-generated Method Stub returnMoney *Rebate; }} Public classCashreturnextendsCashsuper {Private DoubleCondition = 0; Private DoubleMoneyreturn = 0; PublicCashreturn (DoubleConditionDoubleMoneyreturn) { This. Condition =condition; This. Moneyreturn =Moneyreturn; } @Override Public DoubleGetCash (DoubleMoney ) { if(Money >= This. Condition) { Money-= Math.floor (money/condition) *Moneyreturn; } returnMoney ; }} Public classNormalcashextendsCashsuper {@Override Public DoubleGetCash (DoubleMoney ) { //TODO auto-generated Method Stub returnMoney ; }}
View Code
3. Context class for instantiating algorithms and invoking algorithm operations
Public classCashcontext {Cashsuper cs=NULL; Publiccashcontext (String type) {Switch(type) { Case"Normal": CS=NewNormalcash (); Break; Case"Rebate": CS=NewCashrebate (0.8); Break; Case"Return": CS=NewCashreturn (300,80); Break; } } Public DoubleGetResult (DoubleMoney ) { returnCs.getcash (Money); }}
View Code
4, the client class, for testing
Public class Client { publicstaticvoid main (string[] args) { = "return" ; double money =N; New cashcontext (type); System.out.println (Cc.getresult (Money));} }
View Code
Design pattern Start--policy mode