用最简单的例子说明设计模式(二)之模版方法、策略模式、组合模式、观察者模式
public abstract class AbstractWork { protected void getUp() { System.out.println("起床啦!"); } protected abstract void goToWork(); protected abstract void work(); protected abstract void getOffWork(); /* * TemplateMethod,大家都拥有共同的执行步骤 */ public final void newDay() { getUp(); goToWork(); work(); getOffWork(); } } public class BossWork extends AbstractWork { @Override protected void goToWork() { System.out.println("老板开车去上班"); } @Override protected void work() { System.out.println("老板的分配工作给员工"); } @Override protected void getOffWork() { System.out.println("老板开车去下班"); } } public class StaffWork extends AbstractWork { @Override protected void goToWork() { System.out.println("员工做公交去上班"); } @Override protected void work() { System.out.println("员工处理具体工作"); } @Override protected void getOffWork() { System.out.println("员工做公交下班"); } } public class Test { public static void main(String[] args) { BossWork bossWork = new BossWork(); StaffWork staffWork = new StaffWork(); bossWork.newDay(); System.out.println("------------------------"); staffWork.newDay(); } }
public interface AbstractStrategy { //按距离来计算价格 int calculatePrice(int km); } public class BusStrategy implements AbstractStrategy { @Override public int calculatePrice(int km) { int extraTotal = km - 10; int extraFactor = extraTotal / 5; int fraction = extraTotal % 5; int price = 1 + extraTotal % 5; return fraction > 0 ? ++price : price; } } public class TaxiStrategy implements AbstractStrategy { @Override public int calculatePrice(int km) { return km * 2; } } public class Context { private AbstractStrategy strategy; public void setStrategy(AbstractStrategy strategy) { this.strategy = strategy; } public int calclatePrice(int km) { return strategy.calculatePrice(km); } public static void main(String[] strings) { Context calculator = new Context(); calculator.setStrategy(new BusStrategy()); // calculator.setStrategy(new TaxiStrategy()); System.out.println("公交车20km价格:" + calculator.calclatePrice(20)); } }
传统写法
//PriceCalculator 类很明显的问题就是并不是单一职责,首先它承担计算公交车和地铁乘坐价格的职责, //另一个问题就是通过if-else的形式来判断使用哪种计算形式。当我们增加一种出行方式时,如出租车, //那么我们就需要在PriceCalculator 中增加一个方法来计算出租车出行的价格,并且在calculatePrice(int km, int type)函数增加一个判断 public static class PriceCalculator { private static final int TAXI = 3; private static final int BUS = 1; private static final int SUBWAY = 2; public static void main(String[] strings) { PriceCalculator calculator = new PriceCalculator(); System.out.println("做20km公交票价:" + calculator.calculatePrice(20, BUS)); System.out.println("做20km地铁票价:" + calculator.calculatePrice(20, SUBWAY)); } private int busPrice(int km) { return km * 1; } public int taxiPrice(int km) { return km * 7; } /** * 根据不同类型计算 */ int calculatePrice(int km, int type) { if (type == BUS) { return busPrice(km); } else if (type == SUBWAY) { return taxiPrice(km); } return 0; } }
public abstract class File { private String name; public File(String name) { this.name = name; } //操作方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public abstract void watch(); //组合方法 public void add(File file) { throw new UnsupportedOperationException(); } public void remove(File file) { throw new UnsupportedOperationException(); } public File getChild(int position) { throw new UnsupportedOperationException(); } } public class Folder extends File { private List<File> mFileList; public Folder(String name) { super(name); mFileList = new ArrayList<>(); } @Override public void watch() { StringBuffer fileName = new StringBuffer(); for (File file : mFileList) { fileName.append(file.getName() + ";"); } System.out.println("组合模式:这是一个叫" + getName() + "文件夹,包含" + mFileList.size() + "个文件,分别是:" + fileName); } @Override public void add(File file) { mFileList.add(file); } @Override public void remove(File file) { mFileList.remove(file); } @Override public File getChild(int position) { return mFileList.get(position); } } public class TextFile extends File { public TextFile(String name) { super(name); } @Override public void watch() { System.out.println("组合模式:这是一个叫" + getName() + "文本文件"); } } public class testComposite { public static void main(String[] strings) { TextFile textFileA = new TextFile("a.txt"); TextFile textFileB = new TextFile("b.txt"); TextFile textFileC = new TextFile("c.txt"); textFileA.watch(); // textFileA.add(textFileB);//调用会抛我们在抽象接口中写的异常 Folder folder = new Folder("学习资料"); folder.add(textFileA); folder.add(textFileB); folder.add(textFileC); folder.watch(); folder.getChild(1).watch(); Folder folder1 = new Folder("个人资料"); folder1.add(textFileA); folder1.add(textFileB); //可以随便组合 Folder folder2 = new Folder("D盘资料"); folder2.add(folder); folder2.add(folder1); } }
public class ObserverPattern { public interface Observer { void update(String state); } public class ConcreteObserver implements Observer { // 观察者状态 private String observerState; @Override public void update(String state) { // 更新观察者状态,让它与目标状态一致 observerState = state; System.out.println("ConcreteObserver State :" + observerState); } } /** * 抽象订阅者(目标者) * 被观察者 * */ public abstract class Subject { // 保存注册的观察者对象 private List<Observer> mObservers = new ArrayList<>(); //注册观察者对象 public void attach(Observer observer) { mObservers.add(observer); System.out.println("Attached an observer"); } //注销观察者对象 public void detach(Observer observer) { mObservers.remove(observer); } // 通知所有注册的观察者对象 public void nodifyObservers(String newState) { for (Observer observer : mObservers) { observer.update(newState); } } } public class ConcreteSubject extends Subject { private String state; public String getState() { return state; } public void change(String newState) { state = newState; System.out.println("ConcreteSubject State:" + state); //状态发生改变,通知观察者 nodifyObservers(state); } } public static void main(String[] args) { ObserverPattern observerPattern = new ObserverPattern(); ConcreteSubject concreteSubject = observerPattern.new ConcreteSubject(); Observer observer1 = observerPattern.new ConcreteObserver(); Observer observer2 = observerPattern.new ConcreteObserver(); // 将观察者对象注册到目标对象上 concreteSubject.attach(observer1); concreteSubject.attach(observer2); // 改变目标对象的状态 concreteSubject.change("I change"); } }
相关源码:
https://github.com/peiniwan/DesignPattern.git