您的位置:首页 > 其它

简单的工厂模式学习

2016-05-29 17:33 323 查看
1、抽象的操作类:

package com.hhdys.opertion;

/**
* Created by zhangkai on 16/5/29.
*/
public abstract class Operator {
protected int x,y;

public Operator(int x, int y) {
this.x = x;
this.y = y;
}

public abstract int getResult();
}

2、加法操作类:

package com.hhdys.opertion;

/**
* Created by zhangkai on 16/5/29.
*/
public class OperatorAdd extends Operator {

public OperatorAdd(int x, int y) {
super(x, y);
}

@Override
public int getResult() {
return x+y;
}
}

3、减法操作类:

package com.hhdys.opertion;

/**
* Created by zhangkai on 16/5/29.
*/
public class OperatorSub extends Operator {
public OperatorSub(int x, int y) {
super(x, y);
}

@Override
public int getResult() {
return x-y;
}
}

4、工厂类:

package com.hhdys.factory;

import com.hhdys.opertion.Operator;
import com.hhdys.opertion.OperatorAdd;
import com.hhdys.opertion.OperatorSub;

/**
* Created by zhangkai on 16/5/29.
*/
public class OperationFactory {
public static Operator createOpertor(int x,int y,String type){
Operator oper=null;
switch (type){
case "+":
oper=new OperatorAdd(x,y);
break;
case "-":
oper=new OperatorSub(x,y);
break;
default:
break;
}
return oper;
}
}

5、主方法:

package com.hhdys.main;

import com.hhdys.factory.OperationFactory;
import com.hhdys.opertion.Operator;

/**
* Created by zhangkai on 16/5/29.
*/
public class SimpleFactoryMain {
public static void main(String[] args){
System.out.println("简单的工厂模式:解耦合=======");
Operator oper=null;
oper= OperationFactory.createOpertor(10,5,"+");
System.out.println("The '+' result is :"+oper.getResult());
oper=OperationFactory.createOpertor(10,5,"-");
System.out.println("The '-' result is :"+oper.getResult());
}
}

6、运行结果:

简单的工厂模式:解耦合=======
The '+' result is :15
The '-' result is :5

总结:

简单的工厂模式可以将高度耦合的代码进行解耦,比如上述代码,如果需要增加乘法或者除法,只需要新增加类,集成计算抽象类,然后修改工厂模式,增加一个分支即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: