浅谈java设计模式第三篇

该篇主要讲的行为型模式,包括策略模式,模板方法模式(这两类是父类与子类的作用关系);观察者模式,迭代子模式,责任链模式,命令模式(这四类是类与类之间的作用关系);备忘录模式,状态模式(这两类是类状态模式);访问者模式,中介者模式,解释器模式(这三类是中间类和其它类的作用关系)

策略模式:

该模式主要分为多个算法模块和操作算法的用户,每个算法模块都是相互独立的并且可以相互替换, 并且算法的改变不会影响使用的用户,决定权在用户

代码示例
public interface ICaculator {
 public int Caculator(String exp);

}

public abstract class Caculator {

 public int[] change(String exp,String str) {
  
  String[] array = exp.split(str);
  
  int[] arr = new int[2];
  
  arr[0] = Integer.parseInt(array[0]);
  arr[1] = Integer.parseInt(array[1]);
  
  return arr;
 }
}

public class Minus extends Caculator implements ICaculator{

 @Override
 public int Caculator(String exp) {
  int[] array = change(exp,"\\-");
  return array[0] - array[1];
 }
 

}


public class Multi extends Caculator implements ICaculator{

 @Override
 public int Caculator(String exp) {
  int[] array = change(exp,"\\*");
  return array[0]*array[1];
 }

}

public class Plus extends Caculator implements ICaculator{

 @Override
 public int Caculator(String exp) {
  int[] array =  change(exp,"\\+");
  return array[0]+array[1];
 }

}


public class PatterTest {

 public static void main(String[] args) {
  String splus = "8+2";
  ICaculator plus = new Plus();
  System.out.println(plus.Caculator(splus));
  
  String sminus = "8-2";
  ICaculator minus = new Minus();
  System.out.println(minus.Caculator(sminus));
  
  String smulti = "8*2";
  ICaculator multi = new Multi();
  System.out.println(multi.Caculator(smulti));
 }
}

模板方法模式:

该模式主要由一个抽象类和继承该类的子类组成,其中模板类里有一个主方法,和n个抽象方法和实现的方法

代码示例:

public abstract class AbstractCaculator {
 
 public final int caculator(String exp,String opt) {
  
  int[] array = change(exp,opt);
  return caculator(array[0],array[1]);
  
 }
 
 abstract int  caculator(int x,int y);
 
    public int[] change(String exp,String opt) {
     String[] sarry = exp.split(opt);
     
     int[] array = new int[sarry.length];
     
     array[0] = Integer.parseInt(sarry[0]);
     array[1] = Integer.parseInt(sarry[1]);
     return array;
    }

}

public class Minus extends AbstractCaculator{

 @Override
 int caculator(int x, int y) {
  
  return x-y;
 }

}

public class Multi extends AbstractCaculator{

 @Override
 int caculator(int x, int y) {
  
  return x*y;
 }

}

public class Plus extends AbstractCaculator{

 @Override
 int caculator(int x, int y) {
  
  return x+y;
 }

}

public class PatternTest {

 public static void main(String[] args) {
  String exp = "2+8";
  AbstractCaculator plus = new Plus();
  System.out.println(plus.caculator(exp,"\\+"));
  
  String exp1 = "8-2";
  AbstractCaculator minus = new Minus();
  System.out.println(minus.caculator(exp1,"\\-"));
  
  String exp2 = "8*2";
  AbstractCaculator multi = new Multi();
  System.out.println(multi.caculator(exp2,"\\*"));
 }
}


观察者模式

该模式类似于邮件订阅和RSS订阅,当我们所订阅的邮件更新或者改变时,会收到通知;当某个对象发生改变时,其它依赖的对象也会收到通知并做出相应的改变,对应关系主要是一对多

代码示例:

public interface Observer {

 public void receive();
}

public class Observer1 implements Observer{

 @Override
 public void receive() {
  System.out.println("observer1已接收到");
  
 }

}

public class Observer2 implements Observer{

 @Override
 public void receive() {
   System.out.println("observer2已接收到");
  
 }

}

public interface Subject {

 public void add(Observer observer);
 
 public void remove(Observer observer);
 
 public void operation();
 
 public void notifyAllObserver();
 
}

public abstract class AbstractSubject implements Subject{

    private Vector vector = new Vector();
 
 public void add(Observer observer) {
   vector.add(observer);
  
 }
 
 public void remove(Observer observer) {
  
  vector.remove(observer);
 }
 
 public abstract void operation();
 
 @Override
 public void notifyAllObserver() {
  
  Enumeration enume = vector.elements();
  
  while(enume.hasMoreElements()) {
   enume.nextElement().receive();
  }
 }
}

public class MySubject extends AbstractSubject{

 
 public void operation() {
   System.out.println("update self.....");
   notifyAllObserver();
 }
}

public class PatterTest {

 public static void main(String[] args) {
  Subject subject = new MySubject();
  
  subject.add(new Observer1());
  subject.add(new Observer2());
  
  subject.operation();
 }
}


迭代子模式:

该模式主要讲的是顺序访问集合中的对象,一般要求两点:聚集对象(集合类)、迭代访问

代码示例:

public interface Iterator {

 public String previous();
 
 public String next();
 
 public boolean hasNext();
 
 public String first();
}

public class MyIterator implements Iterator{

 private Collection collection;
 
 public MyIterator(Collection collection) {
  
  this.collection = collection;
 }
 
 int pos = -1;
 @Override
 public String previous() {
    if(pos>0) {
       pos--;
    }
    return collection.getElement(pos);
 }

 @Override
 public String next() {
   if(pos     pos++;
   }
   return collection.getElement(pos);
 }

 @Override
 public boolean hasNext() {
  if(pos>=-1&&pos    return true;
  }else {
    return false;
  }
 }

 @Override
 public String first() {
   pos = 0;
  
   return collection.getElement(pos);
 }

}

public interface Collection {

    public MyIterator iterator();
 
 public int size();
 
 public String getElement(int index);
 
 
}

public class MyCollection implements Collection{
 
 private String[] str;
  
 
 public MyCollection(String[] str) {
  this.str = str;
  
 }

 public MyIterator iterator() {
  return new MyIterator(this);
  
 }
 
 @Override
 public int size() {
  
  return str.length;
 }

 @Override
 public String getElement(int index) {
  
  return str[index];
 }

}

public class PatternTest {
 public static void main(String[] args) {
  
     String[] sttr = new String[] {"A","B","C","D"};
  
  Collection collection = new MyCollection(sttr);
  Iterator iterator = collection.iterator();
  
  while(iterator.hasNext()) {
   String str = iterator.next();
   System.out.println(str);
  }
  
 }

}


责任链模式

该模式的特点是某个对象会持有其它对象的引用,其它对象又持有另外的对象的引用,这样就会形成一条链,发出的请求会沿着这条链,但并不确定是哪个对象解决该请求

代码示例:

public interface Handle {

 public void operate();
}

public abstract class AbstractHandle{

 protected Handle handle;

 public Handle getHandle() {
  return handle;
 }

 public void setHandle(Handle handle) {
  this.handle = handle;
 }
 
 
 
}

public class MyHandle extends AbstractHandle implements Handle{

 private String name;
 
 public MyHandle(String name) {
  
  this.name = name;
 }
 
 @Override
 public void operate() {
   System.out.println(name+"解决");
  
   if(handle!=null) {
    getHandle().operate();
   }
  
 }

}

public class PatternTest {
 
 public static void main(String[] args) {
  MyHandle handle1 = new MyHandle("A");
  MyHandle handle2 = new MyHandle("B");
  MyHandle handle3 = new MyHandle("C");
  
  handle1.setHandle(handle2);
  handle2.setHandle(handle3);
  
  handle1.operate();
  
 }

}


命令模式

司令发出命令,命令经过传递,士兵接收到命令,三者只负责干自己的事,并不依赖其它者,命令模式就是实现这三者解耦,并不关心其它对象如何实现

代码示例

public interface Command {

 public void exe();
}

public class Invoker {

 private Command command;
 
 public Invoker(Command command) {
  this.command = command;
 }
 
 public void action() {
  System.out.println("发出指令");
  command.exe();
 }
}

public class MyCommand implements Command{

 private Receiver receiver;
 
 public MyCommand(Receiver receiver) {
   this.receiver=receiver;
 }
 
 @Override
 public void exe() {
  receiver.action();
  
 }

}

public class Receiver {
 
 public void action() {
  
  System.out.println("已收到指令");
 }

}

public class PatterTest {

 public static void main(String[] args) {
  
     Receiver receiver = new Receiver();
    
     Command command = new MyCommand(receiver);
    
     Invoker invoker = new Invoker(command);
     invoker.action();
 }
}


备忘录模式

当需要存储某个对象的属性或者状态时,可以使用该模式,主要包括备忘录类和存储该备忘录的类

代码示例

public class Original {

 private String name;

 public Original(String name) {
  this.name = name;
 }
 
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
 public Memento  createMemento() {
  return new Memento(name);
 }
 
 public void storageMemento(Memento memento) {
  this.name = memento.getName();
 }
}

public class Memento {

 private String name;
 
 public Memento(String name) {
  this.name = name;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
 
}

public class Storage {

 private Memento memento;
 
 public Storage(Memento memento) {
  this.memento = memento;
 }

 public Memento getMemento() {
  return memento;
 }

 public void setMemento(Memento memento) {
  this.memento = memento;
 }
 
 
}

public class PatterTest {

 public static void main(String[] args) {
  String string = "被存储的属性";
  String modString = "修改后的属性";
  
  Original original = new Original(string);
  Memento memento = original.createMemento();
  Storage storage = new Storage(memento);
  
  System.out.println(original.getName());
  original.setName(modString);
  System.out.println(original.getName());
  
  original.storageMemento(storage.getMemento());
  System.out.println(original.getName());
 }
}


状态模式

当一个类的状态改变时,其操作行为也会发生改变,并且其它对象会收到通知,类似QQ,不同的用户状态会对应的不同的操作(隐身,在线,忙碌)

代码示例:

public class State {
 protected String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
 
 public void method1() {
  System.out.println("执行第一种状态的操作");
 }
 
 public void method2() {
  
  System.out.println("执行第二种状态的操作");
 }

}

public class Context {
 
 private State state;
 
 public Context(State state) {
  this.state = state;
 }

 public State getState() {
  return state;
 }

 public void setState(State state) {
  this.state = state;
 }
 
 public void operation() {
  
  if(state.getName().equals("state1")){
   getState().method1();
  }else if(state.getName().equals("state2")) {
   getState().method2();
  }
 }

}

public class PatternTest {

 public static void main(String[] args) {
  State state = new State();
  
  Context context = new Context(state);
  state.setName("state1");
  context.operation();
  
  state.setName("state2");
  context.operation();
 }
}

访问者模式

该模式进行数据结构和作用于结构上的操作解耦,使操作集合能够相对自由的演化,若数据结构易于变化,经常有新的结构对象添加进来则不适合该对象

代码示例:

public interface Visitor {

 public void visit(Subject subject);
}

public interface Subject {

  public void accept(Visitor visit);
 
  public String subject();
}


public class MyVisitor implements Visitor{

 @Override
 public void visit(Subject subject) {
   System.out.println(subject.subject());
  
 }

}

public class MySubject implements Subject{

 @Override
 public void accept(Visitor visit) {
   visit.visit(this);
  
 }

 @Override
 public String subject() {
   return "某数据结构";
 }

}

public class PatternTest {
 public static void main(String[] args) {
  Visitor visitor = new MyVisitor();
  Subject subject = new MySubject();
  
  subject.accept(visitor);
  
 }

}


中介者模式

该模式主要降低类与类之间的耦合度,具体类与类之间的关系交个某个特定的类来维护(和外观者模式区别:中介者模式是把多对多的相互作用转化为一对多的相互作用,做的是简化的操作;而外观模式是提供一个高层次的接口,来统一管理子系统,方便外界调用)

代码示例

public interface Mediator {

 public void createMediator();
 
 public void workAll();
}

public class MyMediator implements Mediator{

 private User user1;
 private User user2;
 
 @Override
 public void createMediator() {
   user1 = new User1(this);
   user2 = new User2(this);
  
 }

 @Override
 public void workAll() {
   user1.work();
   user2.work();
  
 }

}

public abstract class User {

 private Mediator mediator;
 
 public User(Mediator mediator) {
  this.mediator = mediator;
 }
 
 public abstract void work();
 
}

public class User1 extends User{

 public User1(Mediator mediator) {
  super(mediator);
 
 }

 @Override
 public void work() {
  System.out.println("user1执行。。。。。。");
  
 }
}

public class User2 extends User{

 public User2(Mediator mediator) {
  super(mediator);
  
 }
 
 @Override
 public void work() {
   System.out.println("use2执行。。。。。。");
  
 }

}

public class PatterTest {

 public static void main(String[] args) {
  Mediator mediator = new MyMediator();
  mediator.createMediator();
  mediator.workAll();
 }
}


解释器模式

该模式应用面比较窄,主要用在面向对象程序设计的解释器开发中,用来做成各种各种的解释器,如正则表达式解释器

代码示例

public class Context {

 private int num1;
 private int num2;
 
 public Context(int num1,int num2) {
  this.num1 = num1;
  this.num2 = num2;
 }
 
 public int getNum1() {
  return num1;
 }
 public void setNum1(int num1) {
  this.num1 = num1;
 }
 public int getNum2() {
  return num2;
 }
 public void setNum2(int num2) {
  this.num2 = num2;
 }
 
 
}

public interface Expression {

 public int interpret(Context context);
}

public class Minus implements Expression{

 @Override
 public int interpret(Context context) {
  
  return context.getNum1()-context.getNum2();
 }

}

public class Plus implements Expression{

 @Override
 public int interpret(Context context) {
   return context.getNum1()+context.getNum2();
 }

}

public class PatterTest {

 public static void main(String[] args) {
  Context context = new Context(9,6);
  
  Expression exp = new Plus();
  System.out.println(exp.interpret(context));
  
  Expression exp1 = new Minus();
  System.out.println(exp1.interpret(context));
 }
}





你可能感兴趣的:(浅谈java设计模式第三篇)