设计模式之简单工厂模式
看书学习设计模式,书本来源《大话设计模式》,啃一啃怎么样设计程序
在“大话”这本书中写简单工厂模式用计算器为例来说明,其实是最简单的面向接口的编程思维,不依赖与具体的实现,而重点考虑接口。这是比较重要的思维上的转变。
重点:
1、通过继承,造成多态属性,然后在子类中实现父类的接口,在不同的子类中进行不同的接口实现。直接调用实现的接口方法得到最后的值,这一种思维够趣味
2、做增量,尽量不修改之前的,靠增加代码来更改需求
3、最通俗的说法,高内聚,低耦合!
看看我自己照猫画虎写的“工厂计算器”
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class factory { private final String PLUS = "+"; private final String SUB = "-"; private final String RIDE = "*"; private final String DIVIDE = "/"; public factory() throws IOException{ BufferedReader strin=new BufferedReader(new InputStreamReader(System.in)); System.out.print("输入数字:"); String str = strin.readLine(); BufferedReader strin2=new BufferedReader(new InputStreamReader(System.in)); System.out.print("输入运算符号:"); String str2 = strin2.readLine(); Operation op = GetOperation(str2); BufferedReader strin3=new BufferedReader(new InputStreamReader(System.in)); System.out.print("输入数字:"); String str3 = strin3.readLine(); System.out.println("结果是: " + op.getResult(Float.valueOf(str), Float.valueOf(str3))); } private Operation GetOperation(String sign) { switch (sign) { case PLUS: return new SHA_plus(); case SUB: return new SHA_sub(); case RIDE: return new SHA_ride(); case DIVIDE: return new SHA_divide(); } return null; } public static void main(String[] args){ try { new factory(); } catch (IOException e) { e.printStackTrace(); } } } interface Operation { float A = 0; float B = 0; abstract float getResult(float A, float B); } class SHA_plus implements Operation { @Override public float getResult(float A, float B) { return A + B; } } class SHA_sub implements Operation { @Override public float getResult(float A, float B) { return A - B; } } class SHA_ride implements Operation { @Override public float getResult(float A, float B) { return A * B; } } class SHA_divide implements Operation { @Override public float getResult(float A, float B) { if(B != 0){ return A / B; } else return 0; } }
原文地址:http://blog.csdn.net/feishangbeijixing/article/details/46049383