[关闭]
@huangyichun 2017-08-30T15:50:18.000000Z 字数 16247 阅读 932

设计模式

设计模式


面向对象原则

通过封装、继承、多态把程序的耦合度降低。
UML类图: 依赖、组合、继承、实现、聚合、关联

单一职责原则

开放闭合原则

依赖倒置原则

里氏替换原则

:子类必须能够替换掉他们的父类型。
面向对象的语言有三大特性:封装、继承、多态,里氏替换原则就是依赖于继承、多态这两大特性,它的原则就是只要父类能出现的地方子类就能出现,而且不会报错,但是子类能出现的地方,父类不一定能出现,术语就是 —— 抽象。

一个软件实体如果使用的时一个父类的话,那么一定适用于其子类,而且它察觉不出父类和子类的区别。

接口隔离原则

使用多个专门的接口,而不使用单一的总接口,即客户端不应该依赖那些它不需要的接口。
根据接口隔离原则,当一个接口太大时,我们需要将它分割成一些更细小的接口,使用该接口的客户端仅需知道与之相关的方法即可。每一个接口应该承担一种相对独立的角色,不干不该干的事,该干的事都要干。这里的“接口”往往有两种不同的含义:一种是指一个类型所具有的方法特征的集合,仅仅是一种逻辑上的抽象;另外一种是指某种语言具体的“接口”定义,有严格的定义和结构,比如Java语言中的interface。

迪米特法则

也叫最小知识原则,如果两个类不必彼此直接通信,那么这两个类就不应当发生直接的互相作用。如果其中一个类需要调用另一个类的某一个方法的话,可以通过第三者转发这个调用。

简单工厂模式

简单工厂模式解决的问题是如何去实例化一个合适的对象。
简单工厂模式的核心思想就是:有一个专门的类来负责创建实例的过程。
   具体来说,把产品看着是一系列的类的集合,这些类是由某个抽象类或者接口派生出来的一个对象树。而工厂类用来产生一个合适的对象来满足客户的要求。
   如果简单工厂模式所涉及到的具体产品之间没有共同的逻辑,那么我们就可以使用接口来扮演抽象产品的角色;如果具体产品之间有功能的逻辑或,我们就必须把这些共同的东西提取出来,放在一个抽象类中,然后让具体产品继承抽象类。为实现更好复用的目的,共同的东西总是应该抽象出来的。

设计一个计算器的,完成加减乘除操作。

  1. public class Operation {//父类
  2. private double numberA = 0;
  3. private double numberB = 0;
  4. public double getNumberA() {
  5. return numberA;
  6. }
  7. public void setNumberA(double numberA) {
  8. this.numberA = numberA;
  9. }
  10. public double getNumberB() {
  11. return numberB;
  12. }
  13. public void setNumberB(double numberB) {
  14. this.numberB = numberB;
  15. }
  16. public double getResult(){
  17. double result =0;
  18. return result;
  19. }
  20. }
  1. public class OperationAdd extends Operation {//加法操作
  2. @Override
  3. public double getResult() {
  4. return getNumberA() + getNumberB();
  5. }
  6. }
  1. public class OperationDiv extends Operation {//除法操作
  2. @Override
  3. public double getResult() {
  4. if(getNumberB() == 0){
  5. throw new RuntimeException("除数不能为0");
  6. }
  7. return getNumberA() / getNumberB();
  8. }
  9. }
  1. public class OperationMul extends Operation {//乘法操作
  2. @Override
  3. public double getResult() {
  4. return getNumberA() * getNumberB();
  5. }
  6. }
  1. public class OperationSub extends Operation{//减法操作
  2. @Override
  3. public double getResult() {
  4. return getNumberA() - getNumberB();
  5. }
  6. }
  1. public class OperationFactory {//简单工厂模式
  2. /**
  3. * 采用多态,根据传入的参数,返回父类引用子类对象
  4. * @param operate
  5. * @return
  6. */
  7. public static Operation createOperate(String operate) {
  8. Operation operation;
  9. switch (operate) {
  10. case "+":
  11. operation = new OperationAdd();
  12. break;
  13. case "-":
  14. operation = new OperationDiv();
  15. break;
  16. case "*":
  17. operation = new OperationMul();
  18. break;
  19. case "/":
  20. operation = new OperationDiv();
  21. break;
  22. default:
  23. throw new RuntimeException("输入的符号不正确");
  24. }
  25. return operation;
  26. }
  27. }
  1. public class Main {//测试方法
  2. public static void main(String[] args) {
  3. Operation operation = OperationFactory.createOperate("*");
  4. operation.setNumberA(10);
  5. operation.setNumberB(2);
  6. System.out.println(operation.getResult());
  7. }
  8. }

策略模式

定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。

image.png-19.7kB
  这个模式涉及到三个角色:

  ●  环境(Context)角色:持有一个Strategy的引用。

  ●  抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。

  ●  具体策略(ConcreteStrategy)角色:包装了相关的算法或行为。
  
商场打折案例:

  1. /**
  2. * 抽象算法类
  3. */
  4. public interface CashStrategy {
  5. double acceptCash(double money);
  6. }
  1. /**
  2. * 返利200返100等
  3. */
  4. public class CashReturnStrategy implements CashStrategy {
  5. private double moneyCondition = 0.0d;
  6. private double moneyReturn = 0.0d;
  7. public CashReturnStrategy(double moneyCondition, double moneyReturn) {
  8. this.moneyCondition = moneyCondition;
  9. this.moneyReturn = moneyReturn;
  10. }
  11. @Override
  12. public double acceptCash(double money) {
  13. if(money >= moneyCondition){
  14. money = money - (int)(money / moneyCondition) * moneyReturn;
  15. }
  16. return money;
  17. }
  18. }
  1. /**
  2. * 打折
  3. */
  4. public class CashRebateStrategy implements CashStrategy {
  5. private double moneyRebate = 1d;//打折额度
  6. public CashRebateStrategy(double moneyRebate) {
  7. this.moneyRebate = moneyRebate;
  8. }
  9. @Override
  10. public double acceptCash(double money) {
  11. return money * moneyRebate;
  12. }
  13. }
  1. /**
  2. * 正常价格
  3. */
  4. public class CashNomalStrategy implements CashStrategy{
  5. @Override
  6. public double acceptCash(double money) {
  7. return money;
  8. }
  9. }
  1. /**
  2. * 策略模式初始版本
  3. * Created by huang on 17-4-12.
  4. */
  5. public class CashContext {
  6. private CashStrategy cashStrategy;
  7. public CashContext(CashStrategy cashStrategy) {
  8. this.cashStrategy = cashStrategy;
  9. }
  10. public double getResult(double money){
  11. return cashStrategy.acceptCash(money);
  12. }
  13. }
  1. /**
  2. * 策略模式与简单工厂模式结合
  3. */
  4. public class CashContext_2 {
  5. CashStrategy cashStrategy;
  6. public CashContext_2(String type) {
  7. switch (type){
  8. case "正常收费":
  9. cashStrategy = new CashNomalStrategy();
  10. break;
  11. case "满300返100":
  12. cashStrategy = new CashReturnStrategy(300, 100);
  13. break;
  14. case "打8折":
  15. cashStrategy = new CashRebateStrategy(0.8);
  16. break;
  17. }
  18. }
  19. public double getResult(double money){
  20. return cashStrategy.acceptCash(money);
  21. }
  22. }
  1. public class Main {
  2. public static void main(String[] args) {
  3. CashStrategy cashStrategy = new CashReturnStrategy(500,200);
  4. CashContext cashContext = new CashContext(cashStrategy);
  5. double money = cashContext.getResult(750.6);
  6. System.out.println(money);
  7. System.out.println("----------------------");
  8. //策略模式与简单工厂模式结合
  9. CashContext_2 cashContext_2 = new CashContext_2("打8折");
  10. money = cashContext_2.getResult(300);
  11. System.out.println(money );
  12. }
  13. }

Jdk中使用策略模式:

  线程池中当等待队列满时,处理策略有很多种,可以根据需求传入。
http://style.alicharles.com/alicharles/wp-content/uploads/2015/04/20150426232409_12051.png

装饰模式

动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

在装饰模式中的各个角色有:

  (1)抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
  (2)具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。
  (3)装饰(Decorator)角色:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。
  (4)具体装饰(Concrete Decorator)角色:负责给构件对象添加上附加的责任。
image.png-33.4kB

3485420f3e11863872c2072de4a49cba.jpg-49.5kB

IO流采用了装饰者模式,其中InputStream为抽象构件,而FileInputStream, ObjectInputStream等为具体构件,FilterInputStream为装饰角色,它下面的子类,BufferedInputStream,DateInputStream等为具体装饰角色。

  1. /**
  2. * 抽象对象,如果只有一个具体对象可以不要这个类
  3. */
  4. public interface Componet {
  5. void operation();
  6. }
  1. /**
  2. * 具体对象
  3. */
  4. public class PersonComponent implements Componet{
  5. private String name;
  6. public PersonComponent(String name) {
  7. this.name = name;
  8. }
  9. @Override
  10. public void operation() {
  11. System.out.println("装扮对象是"+name);
  12. }
  13. }
  1. /**
  2. * 抽象装饰类
  3. */
  4. public class FineryDecorator implements Componet {
  5. private Componet componet;
  6. public FineryDecorator(Componet componet) {//装饰对象
  7. this.componet = componet;
  8. }
  9. @Override
  10. public void operation() {
  11. componet.operation();
  12. }
  13. }
  1. /**
  2. * 具体装饰类
  3. */
  4. public class LeatherDecorator extends FineryDecorator {
  5. public LeatherDecorator(Componet componet) {
  6. super(componet);
  7. }
  8. @Override
  9. public void operation() {
  10. super.operation();
  11. System.out.println("穿皮鞋");
  12. }
  13. }
  1. /**
  2. *具体装饰类
  3. */
  4. public class BigTrouserDecorator extends FineryDecorator {
  5. public BigTrouserDecorator(Componet componet) {
  6. super(componet);
  7. }
  8. @Override
  9. public void operation() {
  10. super.operation();
  11. System.out.println("穿上垮库");
  12. }
  13. }
  1. /**
  2. *具体装饰类
  3. */
  4. public class TShirtsDecorator extends FineryDecorator{
  5. public TShirtsDecorator(Componet componet) {
  6. super(componet);
  7. }
  8. @Override
  9. public void operation() {
  10. super.operation();
  11. System.out.println("穿上T恤");
  12. }
  13. }
  1. /**
  2. * 测试装饰模式
  3. */
  4. public class Main {
  5. public static void main(String[] args) {
  6. PersonComponent person = new PersonComponent("小菜");
  7. FineryDecorator decorator = new LeatherDecorator(
  8. new TShirtsDecorator(
  9. new BigTrouserDecorator(person)));
  10. decorator.operation();
  11. }
  12. }

享元模式

  1. /**
  2. * 享元类
  3. */
  4. public interface FlyWeight {
  5. String getColor();
  6. void display(Coordinate c);
  7. }
  1. package flyWeight;
  2. /**
  3. * Created by huang on 17-5-12.
  4. */
  5. public class ConcreteFlyWeight implements FlyWeight {
  6. private String color;
  7. public ConcreteFlyWeight(String color) {
  8. this.color = color;
  9. }
  10. @Override
  11. public String getColor() {
  12. return color;
  13. }
  14. @Override
  15. public void display(Coordinate c) {
  16. System.out.println("棋子颜色"+color);
  17. System.out.println("棋子位置"+c.getX() + " "+ c.getY());
  18. }
  19. }
  1. package flyWeight;
  2. /**
  3. * 外部状态UnSharedConcreteFlyWeight
  4. */
  5. public class Coordinate {
  6. private int x, y;
  7. public Coordinate(int x, int y) {
  8. this.x = x;
  9. this.y = y;
  10. }
  11. public int getX() {
  12. return x;
  13. }
  14. public void setX(int x) {
  15. this.x = x;
  16. }
  17. public int getY() {
  18. return y;
  19. }
  20. public void setY(int y) {
  21. this.y = y;
  22. }
  23. }
  1. package flyWeight;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. /**
  5. * 享元工厂类
  6. */
  7. public class FlyWeightFactory {
  8. // ThreadPoolExecutor 线程池,相当于享元工厂
  9. //享元池
  10. private static Map<String, FlyWeight> map = new HashMap<>();
  11. public static FlyWeight getChess(String color){
  12. if(map.get(color) != null)
  13. return map.get(color);
  14. else{
  15. FlyWeight flyWeight = new ConcreteFlyWeight(color);
  16. map.put(color, flyWeight);
  17. return flyWeight;
  18. }
  19. }
  20. }
  1. package flyWeight;
  2. import org.junit.Test;
  3. /**
  4. * Created by huang on 17-5-12.
  5. */
  6. public class Client {
  7. @Test
  8. public void test(){
  9. FlyWeight flyWeight1 = FlyWeightFactory.getChess("红色");
  10. FlyWeight flyWeight2 = FlyWeightFactory.getChess("红色");
  11. System.out.println(flyWeight1 == flyWeight2);
  12. //添加外部状态
  13. flyWeight1.display(new Coordinate(3, 4));
  14. }
  15. }

观察者模式

  1. package observer;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. /**
  5. * 主题
  6. */
  7. public class Subject {
  8. protected List<Observer> list = new ArrayList<>();
  9. public void registerObserver(Observer observer){
  10. list.add(observer);
  11. }
  12. public void removeObserver(Observer observer){
  13. list.remove(observer);
  14. }
  15. public void notifyAllObserver(){
  16. list.forEach(observer -> observer.update(this));
  17. }
  18. }
  1. package observer;
  2. /**
  3. * 观察者
  4. */
  5. public interface Observer {
  6. void update(Subject subject);
  7. }
  1. package observer;
  2. /**
  3. * 具体主题
  4. */
  5. public class ConcreteSubject extends Subject{
  6. private int state;
  7. public int getState() {
  8. return state;
  9. }
  10. public void setState(int state) {
  11. this.state = state;
  12. notifyAllObserver();
  13. }
  14. }
  1. package observer;
  2. /**
  3. * 具体观察者
  4. */
  5. public class ObserverA implements Observer {
  6. private int myState;
  7. public int getMyState() {
  8. return myState;
  9. }
  10. public void setMyState(int myState) {
  11. this.myState = myState;
  12. }
  13. @Override
  14. public void update(Subject subject) {
  15. setMyState(((ConcreteSubject)subject).getState());
  16. }
  17. }
  1. package observer;
  2. /**
  3. *客户端
  4. */
  5. public class Client {
  6. public static void main(String[] args) {
  7. ConcreteSubject subject = new ConcreteSubject();
  8. ObserverA obs1 = new ObserverA();
  9. ObserverA obs2 = new ObserverA();
  10. ObserverA obs3 = new ObserverA();
  11. subject.registerObserver(obs1);
  12. subject.registerObserver(obs2);
  13. subject.registerObserver(obs3);
  14. subject.setState(100);
  15. System.out.println("-------------------");
  16. System.out.println(obs1.getMyState());
  17. System.out.println(obs2.getMyState());
  18. System.out.println(obs3.getMyState());
  19. subject.setState(200);
  20. System.out.println("-------------------");
  21. System.out.println(obs1.getMyState());
  22. System.out.println(obs2.getMyState());
  23. System.out.println(obs3.getMyState());
  24. }
  25. }

工厂模式

工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延续到其子类。
image.png-34.1kB

  1. public interface Car {
  2. void run();
  3. }
  4. public class Audi implements Car {
  5. @Override
  6. public void run() {
  7. System.out.println("奥迪再跑!");
  8. }
  9. }
  10. public class Benz implements Car{
  11. @Override
  12. public void run() {
  13. System.out.println("奔驰再跑");
  14. }
  15. }
  16. public class Byd implements Car {
  17. @Override
  18. public void run() {
  19. System.out.println("比亚迪在跑");
  20. }
  21. }
  22. public interface CarFactory {
  23. Car createCar();
  24. }
  25. public class AudiFactory implements CarFactory {
  26. @Override
  27. public Car createCar() {
  28. return new Audi();
  29. }
  30. }
  31. public class BenzFactory implements CarFactory {
  32. @Override
  33. public Car createCar() {
  34. return new Benz();
  35. }
  36. }
  37. public class BydFactory implements CarFactory {
  38. @Override
  39. public Car createCar() {
  40. return new Byd();
  41. }
  42. }
  43. public class Client {
  44. public static void main(String[] args) {
  45. Car c1 = new AudiFactory().createCar();
  46. c1.run();
  47. Car c2 = new BydFactory().createCar();
  48. c2.run();
  49. }
  50. }

适配器模式

适配器模式,将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由接口不兼容而不能一起工作的那些类可以一起工作。

image.png-20.1kB

组成:
1)Target(目标抽象类):目标抽象类定义客户所需接口,可以是一个抽象类或接口,也可以是具体类。
2)Adapter(适配器类):适配器可以调用另一个接口,作为一个转换器,对Adaptee和Target进行适配,适配器类是适配器模式的核心,在对象适配器中,它通过继承Target并关联一个Adaptee对象使二者产生联系。
3)Adaptee(适配者类):适配者即被适配的角色,它定义了一个已经存在的接口,这个接口需要适配,适配者类一般是一个具体类,包含了客户希望使用的业务方法,在某些情况下可能没有适配者类的源代码。

  1. /**
  2. * 目标抽象类
  3. */
  4. public interface Target {
  5. void handleReq();
  6. }
  7. /**
  8. * 被适配的类,
  9. * 相当于例子中的,PS/2键盘
  10. * Created by huangyichun on 2017/2/7.
  11. */
  12. public class Adaptee {
  13. public void request(){
  14. System.out.println("可以完成用户的需求");
  15. }
  16. }
  17. /*
  18. * 适配器
  19. */
  20. public class Adapter2 implements Target {
  21. private Adaptee adaptee;
  22. public Adapter2(Adaptee adaptee) {
  23. this.adaptee = adaptee;
  24. }
  25. @Override
  26. public void handleReq() {
  27. adaptee.request();
  28. }
  29. }
  30. /**
  31. * 适配器(类适配器方式)
  32. * 相当于usb和ps/2转接口
  33. * Created by huangyichun on 2017/2/7.
  34. */
  35. public class Adapter extends Adaptee implements Target{
  36. @Override
  37. public void handleReq() {
  38. super.request();
  39. }
  40. }
  41. /**
  42. * 被适配的类,
  43. * 相当于例子中的,PS/2键盘
  44. * Created by huangyichun on 2017/2/7.
  45. */
  46. public class Adaptee {
  47. public void request(){
  48. System.out.println("可以完成用户的需求");
  49. }
  50. }
  51. /**
  52. * 客户端类
  53. * 相当于例子中的笔记本,只有USB接口
  54. * Created by huangyichun on 2017/2/7.
  55. */
  56. public class Client {
  57. public static void main(String[] args) {
  58. Client c = new Client();
  59. Adaptee a = new Adaptee();
  60. // Target t = new Adapter();
  61. Target t = new Adapter2(a);
  62. t.handleReq();
  63. }
  64. }

在JDK中使用了适配器模式,如下图

image.png-13kB

将InputStream类型通过InputStreamReader转换成Reader类型,StreamDecoder中包含着InputStream的引用,可以通过源码查看,这是因为Byte类型到char类型需要经过编码。

组合模式

组合模式,将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

image.png-16kB

JDK中AWT包和Swing包的设计是基于组合模式,在这些界面包中为用户提供了大量的容器构件(如Container)和成员构件(如Checkbox、Button和TextComponent等),他们都是继承、关联自抽象组件类Component。

image.png-31.8kB

  1. **
  2. * 抽象组件
  3. * Created by huangyichun on 2017/2/8.
  4. */
  5. public interface AbstractFile {
  6. void killVirus();//杀毒
  7. }
  8. class ImageFile implements AbstractFile{
  9. private String name;
  10. public ImageFile(String name) {
  11. this.name = name;
  12. }
  13. @Override
  14. public void killVirus() {
  15. System.out.println("---图像文件:"+name+",进行查杀!");
  16. }
  17. }
  18. class TextFile implements AbstractFile{
  19. private String name;
  20. public TextFile(String name) {
  21. this.name = name;
  22. }
  23. @Override
  24. public void killVirus() {
  25. System.out.println("---文本文件:"+name+",进行查杀!");
  26. }
  27. }
  28. class VideoFile implements AbstractFile{
  29. private String name;
  30. public VideoFile(String name) {
  31. this.name = name;
  32. }
  33. @Override
  34. public void killVirus() {
  35. System.out.println("---视频文件:"+name+",进行查杀!");
  36. }
  37. }
  38. /**
  39. * 文件夹
  40. */
  41. class Folder implements AbstractFile{
  42. private String name;
  43. //定义容器,用来存放本容器下的子节点
  44. private List<AbstractFile> list = new ArrayList<>();
  45. public Folder(String name) {
  46. this.name = name;
  47. }
  48. public void add(AbstractFile file){
  49. list.add(file);
  50. }
  51. public void remove(AbstractFile file){
  52. list.remove(file);
  53. }
  54. public AbstractFile getChild(int index){
  55. return list.get(index);
  56. }
  57. @Override
  58. public void killVirus() {
  59. System.out.println("---文件夹:"+name+",进行查杀");
  60. for(AbstractFile file : list){
  61. file.killVirus();
  62. }
  63. }
  64. }
  65. public static void main(String[] args) {
  66. AbstractFile f2, f3, f4, f5, f6;
  67. Folder f1 = new Folder("我的收藏");
  68. f2 = new ImageFile("我的大头像.jpg");
  69. f3 = new TextFile("Hello.txt");
  70. f1.add(f2);
  71. f1.add(f3);
  72. Folder f11 = new Folder("电影");
  73. f4 = new VideoFile("笑傲江湖.avi");
  74. f5 = new VideoFile("神雕侠侣.avi");
  75. f11.add(f4);
  76. f11.add(f5);
  77. f1.add(f11);
  78. f1.killVirus();
  79. }

责任链模式

责任链模式: 使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。

diagram.png-25.4kB

package chainOfResponse;

  1. /**
  2. * 抽象类
  3. * Created by huangyichun on 2017/2/8.
  4. */
  5. public abstract class Leader {
  6. //使用protected让子类能够使用
  7. protected String name;
  8. protected Leader nextLeader;
  9. //设定责任链后序处理者
  10. public Leader(String name) {
  11. this.name = name;
  12. }
  13. public void setNextLeader(Leader nextLeader) {
  14. this.nextLeader = nextLeader;
  15. }
  16. /**
  17. * 处理请求的核心业务
  18. *
  19. * @param request
  20. */
  21. public abstract void handleRequest(LeaveRequest request);
  22. }
  1. package chainOfResponse;
  2. /**
  3. * 主任
  4. * Created by huangyichun on 2017/2/8.
  5. */
  6. public class Director extends Leader {
  7. public Director(String name) {
  8. super(name);
  9. }
  10. @Override
  11. public void handleRequest(LeaveRequest request) {
  12. if (request.getLeaveDays() < 3) {
  13. System.out.println("员工:" + request.getEmpName() + " 请假" + request.getLeaveDays() + " " +
  14. "理由:" + request.getReason());
  15. System.out.println("主任:" + name + "审批通过");
  16. } else {
  17. if (this.nextLeader != null) {
  18. this.nextLeader.handleRequest(request);
  19. }
  20. }
  21. }
  22. }
  23. package chainOfResponse;
  24. /**
  25. * 经理
  26. * Created by huangyichun on 2017/2/8.
  27. */
  28. public class Manager extends Leader {
  29. public Manager(String name) {
  30. super(name);
  31. }
  32. @Override
  33. public void handleRequest(LeaveRequest request) {
  34. if(request.getLeaveDays() >= 3 && request.getLeaveDays() < 10){
  35. System.out.println("员工:"+request.getEmpName()+" 请假"+request.getLeaveDays()+" " +
  36. "理由:"+request.getReason());
  37. System.out.println("经理:"+name+"审批通过");
  38. }else{
  39. if(this.nextLeader != null){
  40. this.nextLeader.handleRequest(request);
  41. }
  42. }
  43. }
  44. }
  45. package chainOfResponse;
  46. /**
  47. * 总经理
  48. * Created by huangyichun on 2017/2/8.
  49. */
  50. public class GeneralManager extends Leader {
  51. public GeneralManager(String name) {
  52. super(name);
  53. }
  54. @Override
  55. public void handleRequest(LeaveRequest request) {
  56. if(request.getLeaveDays() >= 10 && request.getLeaveDays() < 30){
  57. System.out.println("员工:"+request.getEmpName()+" 请假"+request.getLeaveDays()+" " +
  58. "理由:"+request.getReason());
  59. System.out.println("总经理:"+name+"审批通过");
  60. }else{
  61. System.out.println("莫非想辞职居然请假"+request.getLeaveDays());
  62. }
  63. }
  64. }
  1. package chainOfResponse;
  2. /**
  3. * 封装请假的基本信息
  4. * Created by huangyichun on 2017/2/8.
  5. */
  6. public class LeaveRequest {
  7. private String empName;
  8. private int leaveDays;
  9. private String reason;
  10. public LeaveRequest(String empName, int leaveDays, String reason) {
  11. this.empName = empName;
  12. this.leaveDays = leaveDays;
  13. this.reason = reason;
  14. }
  15. public String getEmpName() {
  16. return empName;
  17. }
  18. public void setEmpName(String empName) {
  19. this.empName = empName;
  20. }
  21. public int getLeaveDays() {
  22. return leaveDays;
  23. }
  24. public void setLeaveDays(int leaveDays) {
  25. this.leaveDays = leaveDays;
  26. }
  27. public String getReason() {
  28. return reason;
  29. }
  30. public void setReason(String reason) {
  31. this.reason = reason;
  32. }
  33. }
  1. package chainOfResponse;
  2. /**
  3. * Created by huangyichun on 2017/2/8.
  4. */
  5. public class Client {
  6. public static void main(String[] args) {
  7. Leader a = new Director("张三");
  8. Leader b = new Manager("李四");
  9. Leader c = new GeneralManager("王五");
  10. //组织责任链对象的关系
  11. a.setNextLeader(b);
  12. b.setNextLeader(c);
  13. //开始请假操作
  14. LeaveRequest request = new LeaveRequest("Tom",1,"回家过年");
  15. a.handleRequest(request);
  16. }
  17. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注