最近在学习大话设计模式,写一下自己的学习体会和实现小例子。
理解:自定义一个接口,根据不同的需求创建实现类,而工厂模式主要解决接口选择的问题,根据条件的不同动态的创建实例
简单实例(计算器):
接口:
public interface Calculation { double getResult(double a, double b) throws Exception; }
实现类:加:
public class Add implements Calculation { @Override public double getResult(double a, double b) { return a + b; } }
减:
public class Reduce implements Calculation { @Override public double getResult(double a, double b) { return a - b; } }
乘:
public class Ride implements Calculation { @Override public double getResult(double a, double b) { return a * b; } }
除:
public class Divide implements Calculation { @Override public double getResult(double a, double b) throws Exception { if (b != 0) { return a / b; } else { throw new Exception("两数相除,除数不能为 0"); } } }
id 配置:
(接口变量默认public static final,简单配置)
public interface Constant { int add = 1; int reduce = 2; int ride = 3; int divide = 4; }
工厂类:
public class CalculationFactory { public static Calculation createCalution(int id) { Calculation calculation = null; switch (id) { case Constant.add: calculation = new Add(); break; case Constant.reduce: calculation = new Reduce(); break; case Constant.ride: calculation = new Ride(); break; case Constant.divide: calculation = new Divide(); break; default: } return calculation; } }
调用类:
public class Main { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { while (true) { double a; double b; int c; try { System.out.println("请输入第一个数字"); a = scanner.nextDouble(); System.out.println("请输入第二个数字"); b = scanner.nextDouble(); System.out.println("1:加 2:减 3:乘 4:除"); c = scanner.nextInt(); System.out.println("运算结果为:"); } catch (Exception e) { break; } Calculation calculation = CalculationFactory.createCalution(c); if (calculation != null) { try { System.out.println(calculation.getResult(a, b) + ""); } catch (Exception e) { System.out.println(e.getMessage()); } } } } }