计算器实例:
(一)简单工厂:
abstract class Operate
{
int Numb1,Numb2;
abstract double getResult();
}
class Jia extends Operate
{
double getResult()
{
return (Numb1+Numb2);
}
}
class Jian extends Operate
{
double getResult() {
return (Numb1-Numb2);
}
}
class Cheng extends Operate
{
double getResult() {
return (Numb1*Numb2);
}
}
class Chu extends Operate
{
double getResult() {
try
{
return (Numb1/Numb2);
}
catch(ArithmeticException e) {
System.out.println("除数不能为零!");
}
return 0;
}
}
class Ifactory
{
Operate createoperate(String ysf)
{Operate Ope=null;
switch(ysf)
{case"+":
Ope=new Jia();break;
case"-":
Ope=new Jian();break;
case"*":
Ope=new Cheng();break;
case"/":
Ope=new Chu();break;
}
return Ope;
}
}
客户端代码:
public class aaa {
public static void main(String[] args) {
Ifactory factory=new Ifactory();
Operate a=factory.createoperate("/");
a.Numb1=1;
a.Numb2=0;
System.out.println(a.getResult());
}
}
简单工厂的UML类图:
用简单工厂设计计算器,如若要增加新的运算功能,必须要修改工厂类,即再加别的case分支来满足,这就等于说不但对拓展开放了,而且对修改也开放了。这违背了开放-封闭原则。由此,便产生了工厂方法来解决这一问题。
(二)工厂方法:
interface Factory
{
Operate Createopeate();
}
abstract class Operate
{
int Numb1,Numb2;
abstract double getResult();
}
class Jia extends Operate
{
double getResult()
{
return (Numb1+Numb2);
}
}
class Jiafactory implements Factory
{
public Operate Createopeate() {
return new Jia();
}
}
class Jian extends Operate
{
double getResult() {
return (Numb1-Numb2);
}
}
class Jianfactory implements Factory
{
public Operate Createopeate() {
return new Jian();
}
}
class Cheng extends Operate
{
double getResult() {
return (Numb1*Numb2);
}
}
class Chengfactory implements Factory
{
public Operate Createopeate() {
return new Cheng();
}
}
class Chu extends Operate
{
double getResult() {
try
{
return (Numb1/Numb2);
}
catch(ArithmeticException e) {
System.out.println("除数不能为零!");
}
return 0;
}
}
class Chufactory implements Factory
{
public Operate Createopeate() {
return new Chu();
}
}
客户端代码:
```java
public class aaa {
public static void main(String[] args) {
Factory factory=new Jiafactory();
Operate operate=factory.Createopeate();
operate.Numb1=10;
operate.Numb2=20;
System.out.println(operate.getResult());
}
}
工厂方法UML类图: