Simple Factory mode

Source: Internet
Author: User

Learn a simple factory with an example of a calculator

1. Operation Operation Class

 Public classoperation{Private Double_numbera=0; Private Double_numberb=0;  Public DoubleNumbera {Get{return_numbera}Set{_numbera=value;} }      Public DoubleNumberb {Get{return_numberb}Set{_numberb=value;} }     Public Virtual DoubleGetResult () //virtual method, convenient subclass rewrite {Doubleresult=0; returnresult; }}

2, Subtraction class

classOpertionadd:operation//Addition Class{     Public Override DoubleGetResult () {Doubleresult=0; Result=numbera+Numberb; returnresult; }}classOpertionsub:operation//Subtraction Class{     Public Override DoubleGetResult () {Doubleresult=0; Result=numbera-Numberb; returnresult; }}classOpertionmul:operation//Multiplication Class{     Public Override DoubleGetResult () {Doubleresult=0; Result=numbera*Numberb; returnresult; }}classOpertiondiv:operation//Division class{     Public Override DoubleGetResult () {Doubleresult=0; if(numberb==0)        {            Throw NewException ("the divisor cannot be 0"); } result=numbera/Numberb; returnresult; }}

3, simple Operation factory class

 Public classoperationfactory{ Public StaticOperation Createoperate (stringoperate) {Operation Oper=NULL; Switch(operate) { Case "+": Oper=NewOperationadd ();  Break;  Case "-": Oper=Newoperationsub ();  Break;  Case "*": Oper=NewOperationmul ();  Break;  Case "/": Oper=NewOperationdiv ();  Break; }    }}

4. Client code

Operation Oper;oper=operationfactory.createoperate ("+"); Oper. Numbera=1; oper. Numberb=2; Double Result=oper. GetResult ();

Simple Factory mode

Related Article

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.