Introduction to factory Model

Source: Internet
Author: User

A simple calculator example to describe the factory Mode

Operator public interface

Package com. ISS. factory;


Public interface operator {
Public int getresult (int x, int y );


}


Add. Java

Package com. ISS. factory;


Public class add implements operator {


@ Override
Public int getresult (int x, int y ){
// Todo auto-generated method stub
Return X + Y;
}


}

Minus. Java

Package com. ISS. factory;


Public class minus implements operator {


@ Override
Public int getresult (int x, int y ){
// Todo auto-generated method stub
Return x-y;
}


}

Mul. Java

Package com. ISS. factory;


Public class Mul implements operator {


@ Override
Public int getresult (int x, int y ){
// Todo auto-generated method stub
Return x * Y;
}


}


Divide. Java

Package com. ISS. factory;


Public class divide implements operator {


@ Override
Public int getresult (int x, int y ){
// Todo auto-generated method stub
Return x/y;
}


}


Operatorfactory. Class

Package com. ISS. factory;


Public class operatorfactory {
Private Static Operator = NULL;


Public static operator getoperator (string OP ){


If (OP = "+ "){
Operator = new add ();
} Else if (OP = "-"){
Operator = new minus ();
} Else if (OP = "*"){
Operator = new MUL ();
} Else if (OP = "/"){
Operator = new divide ();
} Else {
Return NULL;
}


Return operator;


}


}


Test. Java

Package com. ISS. factory;


Public class test {
Public static void main (string [] ARGs ){
Operator = operatorfactory. getoperator ("+ ");
System. Out. println (operator. getresult (10, 20 ));
}


}

Conclusion: The factory model mainly utilizes the object-oriented polymorphism feature. The program has multiple options during actual running!





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.