Design Mode 4---policy mode

Source: Internet
Author: User

Shopping malls in the calculation of prices, often for a lot of promotional methods.

The essence of object-oriented is that the abstraction of the same parts is in line with the human way of thinking.

When there are many kinds of algorithms that can be replaced (such as the commodity price algorithm), you can use the policy mode.

UML diagram:

Strategy is a strategy base class, and the calculation of all commodity prices is an algorithm.

The contextinterface is used to encapsulate specific algorithms, thus separating the client from the price calculation.

Define the interface for Strtegy:

  

 Package Com.jayfulmath.designpattern.strategy;  Public Interface Icashsuper {    publicdouble acceptcash (double money );}

Then there are the various promotion algorithms:

 PackageCom.jayfulmath.designpattern.strategy; Public classCashsaleImplementsIcashsuper {Private DoubleMonryrate =1d;  PublicCashsale (String monryratestr) { This. monryrate =double.parsedouble (MONRYRATESTR); } @Override Public DoubleAcceptcash (DoubleMoney ) {                returnmonryrate*Money ; }}
 PackageCom.jayfulmath.designpattern.strategy; Public classCashreturnImplementsIcashsuper {Private DoubleMoneycondition = 0.0d; Private DoubleMoneyreturn = 0.0d;  PublicCashreturn (String moneyconditionstr, String moneyreturnstr) {Try{moneycondition=double.parsedouble (MONEYCONDITIONSTR); Moneyreturn=double.parsedouble (MONEYRETURNSTR); } Catch(Exception e) {System.out.println ("Parse condition wrong:" +moneycondition+ "Moneyreturn:" +Moneyreturn); }} @Override Public DoubleAcceptcash (DoubleMoney ) {        Doubleresult = 0.0d; if(money>=moneycondition) {Result= Money-math.floor (money/moneycondition) *Moneyreturn; }        returnresult; }}
 PackageCom.jayfulmath.designpattern.strategy; Public classCashreturnImplementsIcashsuper {Private DoubleMoneycondition = 0.0d; Private DoubleMoneyreturn = 0.0d;  PublicCashreturn (String moneyconditionstr, String moneyreturnstr) {Try{moneycondition=double.parsedouble (MONEYCONDITIONSTR); Moneyreturn=double.parsedouble (MONEYRETURNSTR); } Catch(Exception e) {System.out.println ("Parse condition wrong:" +moneycondition+ "Moneyreturn:" +Moneyreturn); }} @Override Public DoubleAcceptcash (DoubleMoney ) {        Doubleresult = 0.0d; if(money>=moneycondition) {Result= Money-math.floor (money/moneycondition) *Moneyreturn; }        returnresult; }}
 Package Com.jayfulmath.designpattern.strategy;  Public class Implements icashsuper {    @Override    publicdouble acceptcash (double  Money) {        return money ;    }}

Contextinterface method encapsulated in factory class:

 PackageCom.jayfulmath.designpattern.strategy;ImportJava.text.DecimalFormat; Public classCashcontext {PrivateIcashsuper cs =NULL;  Publiccashcontext (String type) {System.out.println ("Product Promotion" +type); Switch(type) { Case"Normal": CS=NewCashnormal ();  Break;  Case"Return to Reach 300": CS=NewCashreturn ("300.0", "100.0");  Break;  Case"80%sale": CS=NewCashsale ("0.8");  Break; default: System.out.println ("There is no product promotion to match");  Break; }    }     Public DoubleGetResult (DoubleMoney ) {        Doubleresult =Money ; if(cs! =NULL) {result=Cs.acceptcash (Money); } String resultstr=NewDecimalFormat ("0.00"). Format (result); Result=double.parsedouble (RESULTSTR); returnresult; }}
 PackageCom.jayfulmath.designpattern.strategy;ImportJava.text.DecimalFormat; Public classCashcontext {PrivateIcashsuper cs =NULL;  Publiccashcontext (String type) {System.out.println ("Product Promotion" +type); Switch(type) { Case"Normal": CS=NewCashnormal ();  Break;  Case"Return to Reach 300": CS=NewCashreturn ("300.0", "100.0");  Break;  Case"80%sale": CS=NewCashsale ("0.8");  Break; default: System.out.println ("There is no product promotion to match");  Break; }    }     Public DoubleGetResult (DoubleMoney ) {        Doubleresult =Money ; if(cs! =NULL) {result=Cs.acceptcash (Money); } String resultstr=NewDecimalFormat ("0.00"). Format (result); Result=double.parsedouble (RESULTSTR); returnresult; }}

Main method:

 PackageCom.jayfulmath.designpattern.strategy;Importcom.jayfulmath.designpattern.main.BasicExample; Public classStrategymainextendsbasicexample {@Override Public voidStartdemo () {//TODO auto-generated Method StubCashcontext cc =NULL; Commodity shoes=NewCommodity ("shoe", 123.5, 5); Commodity cloths=NewCommodity ("cloths", 323.2, 6); Commodity Apple=NewCommodity ("Apple", 15.62, 25); CC=NewCashcontext ("70%sale"); Doubleresult =Cc.getresult (Shoes.gettotalprice ()+ cloths.gettotalprice () +Apple.gettotalprice ()); System.out.println ("Total Price is:" +result); }}

Finally, the product Category:

Package Com.jayfulmath.designpattern.strategy;public class Commodity {public String _name;private double _price; private int _count;public Double Get_price () {return _price;} public void Set_price (double _price) {this._price = _price;} Public String get_name () {return _name;} public void Set_name (String _name) {this._name = _name;} /** * @return the _count */public int get_count () {return _count;} /** * @param _count the _count to set */public void Set_count (int _count) {this._count = _count;} Public commodity (String _name, double _price, int _count) {this._name = _name;this._price = _price;this._count = _count; System.out.println ("Buy goods" +_name+ "" +_count+ "+" unit Price "+_price); Public double Gettotalprice () {return _count*_price;}}

Operation Result:

Buy goods Shoe 5 unit price 123.5 buy Item Cloths 6 Unit price 323.2 buy item Apple 25 Unit price 15.62 Item promotion 80%saletotal prices is:2357.76

The strategy pattern is characterized by abstract encapsulation of various strategies (or algorithms) and further encapsulation through the Contextinterface factory class,

The client only needs to tell Contextinterface which algorithm to use.

Design Mode 4---policy mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.