一、设计模式的分类

二、设计模式的六大原则总原则:开闭原则(Open Close Principle)
1、单一职责原则
2、里氏替换原则(Liskov Substitution Principle)
3、依赖倒转原则(Dependence Inversion Principle)
4、接口隔离原则(Interface Segregation Principle)
5、迪米特法则(最少知道原则)(Demeter Principle)
6、合成复用原则(Composite Reuse Principle)
三、Java的23中设计模式A、创建模式
0、简单工厂模式
01、普通

[java] view plaincopy
- public interface Sender {
- public void Send();
- }
[java] view plaincopy
- public class MailSender implements Sender {
- @Override
- public void Send() {
- System.out.println("this is mailsender!");
- }
- }
[java] view plaincopy
- public class SmsSender implements Sender {
- @Override
- public void Send() {
- System.out.println("this is sms sender!");
- }
- }
[java] view plaincopy
- public class SendFactory {
- public Sender produce(String type) {
- if ("mail".equals(type)) {
- return new MailSender();
- } else if ("sms".equals(type)) {
- return new SmsSender();
- } else {
- System.out.println("请输入正确的类型!");
- return null;
- }
- }
- }
- public class FactoryTest {
- public static void main(String[] args) {
- SendFactory factory = new SendFactory();
- Sender sender = factory.produce("sms");
- sender.Send();
- }
- }
02、多个方法

[java] view plaincopypublic class SendFactory {
public Sender produceMail(){
- return new MailSender();
- }
- public Sender produceSms(){
- return new SmsSender();
- }
- }
[java] view plaincopy
- public class FactoryTest {
- public static void main(String[] args) {
- SendFactory factory = new SendFactory();
- Sender sender = factory.produceMail();
- sender.Send();
- }
- }
03、多个静态方法
[java] view plaincopy
- public class SendFactory {
- public static Sender produceMail(){
- return new MailSender();
- }
- public static Sender produceSms(){
- return new SmsSender();
- }
- }
[java] view plaincopy
- public class FactoryTest {
- public static void main(String[] args) {
- Sender sender = SendFactory.produceMail();
- sender.Send();
- }
- }
1、工厂方法模式(Factory Method)

[java] view plaincopy
- public interface Sender {
- public void Send();
- }
[java] view plaincopy
- public class MailSender implements Sender {
- @Override
- public void Send() {
- System.out.println("this is mailsender!");
- }
- }
[java] view plaincopy
- public class SmsSender implements Sender {
- @Override
- public void Send() {
- System.out.println("this is sms sender!");
- }
- }
[java] view plaincopy
- public class SendMailFactory implements Provider {
- @Override
- public Sender produce(){
- return new MailSender();
- }
- }
[java] view plaincopy
- public class SendSmsFactory implements Provider{
- @Override
- public Sender produce() {
- return new SmsSender();
- }
- }
[java] view plaincopy
- public interface Provider {
- public Sender produce();
- }
[java] view plaincopy
- public class Test {
- public static void main(String[] args) {
- Provider provider = new SendMailFactory();
- Sender sender = provider.produce();
- sender.Send();
- }
- }
2、抽象工厂模式
工厂方法模式:一个抽象产品类,可以派生出多个具体产品类。 一个抽象工厂类,可以派生出多个具体工厂类。 每个具体工厂类只能创建一个具体产品类的实例。抽象工厂模式:多个抽象产品类,每个抽象产品类可以派生出多个具体产品类。 一个抽象工厂类,可以派生出多个具体工厂类。 每个具体工厂类可以创建多个具体产品类的实例,也就是创建的是一个产品线下的多个产品。 区别:工厂方法模式只有一个抽象产品类,而抽象工厂模式有多个。 工厂方法模式的具体工厂类只能创建一个具体产品类的实例,而抽象工厂模式可以创建多个。工厂方法创建 "一种" 产品,他的着重点在于"怎么创建",也就是说如果你开发,你的大量代码很可能围绕着这种产品的构造,初始化这些细节上面。也因为如此,类似的产品之间有很多可以复用的特征,所以会和模版方法相随。
抽象工厂需要创建一些列产品,着重点在于"创建哪些"产品上,也就是说,如果你开发,你的主要任务是划分不同差异的产品线,并且尽量保持每条产品线接口一致,从而可以从同一个抽象工厂继承。
对于java来说,你能见到的大部分抽象工厂模式都是这样的:---它的里面是一堆工厂方法,每个工厂方法返回某种类型的对象。比如说工厂可以生产鼠标和键盘。那么抽象工厂的实现类(它的某个具体子类)的对象都可以生产鼠标和键盘,但可能工厂A生产的是罗技的键盘和鼠标,工厂B是微软的。这样A和B就是工厂,对应于抽象工厂;每个工厂生产的鼠标和键盘就是产品,对应于工厂方法;用了工厂方法模式,你替换生成键盘的工厂方法,就可以把键盘从罗技换到微软。但是用了抽象工厂模式,你只要换家工厂,就可以同时替换鼠标和键盘一套。如果你要的产品有几十个,当然用抽象工厂模式一次替换全部最方便(这个工厂会替你用相应的工厂方法)所以说抽象工厂就像工厂,而工厂方法则像是工厂的一种产品生产线
3、单例模式(Singleton)
[java] view plaincopy
- public class Singleton {
- /* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */
- private static Singleton instance = null;
- /* 私有构造方法,防止被实例化 */
- private Singleton() {
- }
- /* 静态工程方法,创建实例 */
- public static Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- /* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */
- public Object readResolve() {
- return instance;
- }
- }
这个类可以满足基本要求,但是,像这样毫无线程安全保护的类,如果我们把它放入多线程的环境下,肯定就会出现问题了,如何解决?我们首先会想到对getInstance方法加synchronized关键字,如下:
[java] view plaincopy
- public static synchronized Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
[java] view plaincopy
- public static Singleton getInstance() {
- if (instance == null) {
- synchronized (instance) {
- if (instance == null) {
- instance = new Singleton();
- }
- }
- }
- return instance;
- }
[java] view plaincopy
- private static class SingletonFactory{
- private static Singleton instance = new Singleton();
- }
- public static Singleton getInstance(){
- return SingletonFactory.instance;
- }
[java] view plaincopy
- public class Singleton {
- /* 私有构造方法,防止被实例化 */
- private Singleton() {
- }
- /* 此处使用一个内部类来维护单例 */
- private static class SingletonFactory {
- private static Singleton instance = new Singleton();
- }
- /* 获取实例 */
- public static Singleton getInstance() {
- return SingletonFactory.instance;
- }
- /* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */
- public Object readResolve() {
- return getInstance();
- }
- }
[java] view plaincopy
- public class SingletonTest {
- private static SingletonTest instance = null;
- private SingletonTest() {
- }
- private static synchronized void syncInit() {
- if (instance == null) {
- instance = new SingletonTest();
- }
- }
- public static SingletonTest getInstance() {
- if (instance == null) {
- syncInit();
- }
- return instance;
- }
- }
[java] view plaincopy
- public class SingletonTest {
- private static SingletonTest instance = null;
- private Vector properties = null;
- public Vector getProperties() {
- return properties;
- }
- private SingletonTest() {
- }
- private static synchronized void syncInit() {
- if (instance == null) {
- instance = new SingletonTest();
- }
- }
- public static SingletonTest getInstance() {
- if (instance == null) {
- syncInit();
- }
- return instance;
- }
- public void updateProperties() {
- SingletonTest shadow = new SingletonTest();
- properties = shadow.getProperties();
- }
- }
4、建造者模式(Builder)
5、原型模式(Prototype)
[java] view plaincopy
- public class Prototype implements Cloneable {
- public Object clone() throws CloneNotSupportedException {
- Prototype proto = (Prototype) super.clone();
- return proto;
- }
- }
[java] view plaincopy
- public class Prototype implements Cloneable, Serializable {
- private static final long serialVersionUID = 1L;
- private String string;
- private SerializableObject obj;
- /* 浅复制 */
- public Object clone() throws CloneNotSupportedException {
- Prototype proto = (Prototype) super.clone();
- return proto;
- }
- /* 深复制 */
- public Object deepClone() throws IOException, ClassNotFoundException {
- /* 写入当前对象的二进制流 */
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(bos);
- oos.writeObject(this);
- /* 读出二进制流产生的新对象 */
- ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
- ObjectInputStream ois = new ObjectInputStream(bis);
- return ois.readObject();
- }
- public String getString() {
- return string;
- }
- public void setString(String string) {
- this.string = string;
- }
- public SerializableObject getObj() {
- return obj;
- }
- public void setObj(SerializableObject obj) {
- this.obj = obj;
- }
- }
- class SerializableObject implements Serializable {
- private static final long serialVersionUID = 1L;
- }
要实现深复制,需要采用流的形式读入当前对象的二进制输入,再写出二进制数据对应的对象。
B、结构模式(7种)

6、适配器模式
01、类的适配器模式

[java] view plaincopy
- public class Source {
- public void method1() {
- System.out.println("this is original method!");
- }
- }
[java] view plaincopy
- public interface Targetable {
- /* 与原类中的方法相同 */
- public void method1();
- /* 新类的方法 */
- public void method2();
- }
[java] view plaincopy
- public class Adapter extends Source implements Targetable {
- @Override
- public void method2() {
- System.out.println("this is the targetable method!");
- }
- }
[java] view plaincopy
- public class AdapterTest {
- public static void main(String[] args) {
- Targetable target = new Adapter();
- target.method1();
- target.method2();
- }
- }
this is the targetable method!
02、对象的适配器模式

[java] view plaincopy
- public class Wrapper implements Targetable {
- private Source source;
- public Wrapper(Source source){
- super();
- this.source = source;
- }
- @Override
- public void method2() {
- System.out.println("this is the targetable method!");
- }
- @Override
- public void method1() {
- source.method1();
- }
- }
[java] view plaincopy
- public class AdapterTest {
- public static void main(String[] args) {
- Source source = new Source();
- Targetable target = new Wrapper(source);
- target.method1();
- target.method2();
- }
- }
03、接口的适配器模式

[java] view plaincopy
- public interface Sourceable {
- public void method1();
- public void method2();
- }
[java] view plaincopy
- public abstract class Wrapper2 implements Sourceable{
- public void method1(){}
- public void method2(){}
- }
[java] view plaincopy
- public class SourceSub1 extends Wrapper2 {
- public void method1(){
- System.out.println("the sourceable interface's first Sub1!");
- }
- }
[java] view plaincopy
- public class SourceSub2 extends Wrapper2 {
- public void method2(){
- System.out.println("the sourceable interface's second Sub2!");
- }
- }
[java] view plaincopy
- public class WrapperTest {
- public static void main(String[] args) {
- Sourceable source1 = new SourceSub1();
- Sourceable source2 = new SourceSub2();
- source1.method1();
- source1.method2();
- source2.method1();
- source2.method2();
- }
- }
the sourceable interface's second Sub2!
7、装饰模式(Decorator)

[java] view plaincopy
- public interface Sourceable {
- public void method();
- }
[java] view plaincopy
- public class Source implements Sourceable {
- @Override
- public void method() {
- System.out.println("the original method!");
- }
- }
[java] view plaincopy
- public class Decorator implements Sourceable {
- private Sourceable source;
- public Decorator(Sourceable source){
- super();
- this.source = source;
- }
- @Override
- public void method() {
- System.out.println("before decorator!");
- source.method();
- System.out.println("after decorator!");
- }
- }
[java] view plaincopy
- public class DecoratorTest {
- public static void main(String[] args) {
- Sourceable source = new Source();
- Sourceable obj = new Decorator(source);
- obj.method();
- }
- }
the original method!
after decorator!
8、代理模式(Proxy)

[java] view plaincopy
- public interface Sourceable {
- public void method();
- }
[java] view plaincopy
- public class Source implements Sourceable {
- @Override
- public void method() {
- System.out.println("the original method!");
- }
- }
[java] view plaincopy
- public class Proxy implements Sourceable {
- private Source source;
- public Proxy(){
- super();
- this.source = new Source();
- }
- @Override
- public void method() {
- before();
- source.method();
- atfer();
- }
- private void atfer() {
- System.out.println("after proxy!");
- }
- private void before() {
- System.out.println("before proxy!");
- }
- }
[java] view plaincopy
- public class ProxyTest {
- public static void main(String[] args) {
- Sourceable source = new Proxy();
- source.method();
- }
- }
the original method!
after proxy!
9、外观模式(Facade)

[java] view plaincopy
- public class CPU {
- public void startup(){
- System.out.println("cpu startup!");
- }
- public void shutdown(){
- System.out.println("cpu shutdown!");
- }
- }
[java] view plaincopy
- public class Memory {
- public void startup(){
- System.out.println("memory startup!");
- }
- public void shutdown(){
- System.out.println("memory shutdown!");
- }
- }
[java] view plaincopy
- public class Disk {
- public void startup(){
- System.out.println("disk startup!");
- }
- public void shutdown(){
- System.out.println("disk shutdown!");
- }
- }
[java] view plaincopy
- public class Computer {
- private CPU cpu;
- private Memory memory;
- private Disk disk;
- public Computer(){
- cpu = new CPU();
- memory = new Memory();
- disk = new Disk();
- }
- public void startup(){
- System.out.println("start the computer!");
- cpu.startup();
- memory.startup();
- disk.startup();
- System.out.println("start computer finished!");
- }
- public void shutdown(){
- System.out.println("begin to close the computer!");
- cpu.shutdown();
- memory.shutdown();
- disk.shutdown();
- System.out.println("computer closed!");
- }
- }
[java] view plaincopy
- public class User {
- public static void main(String[] args) {
- Computer computer = new Computer();
- computer.startup();
- computer.shutdown();
- }
- }
cpu startup!
memory startup!
disk startup!
start computer finished!
begin to close the computer!
cpu shutdown!
memory shutdown!
disk shutdown!
computer closed!
10、桥接模式(Bridge)

[java] view plaincopy
- public interface Sourceable {
- public void method();
- }
[java] view plaincopy
- public class SourceSub1 implements Sourceable {
- @Override
- public void method() {
- System.out.println("this is the first sub!");
- }
- }
[java] view plaincopy
- public class SourceSub2 implements Sourceable {
- @Override
- public void method() {
- System.out.println("this is the second sub!");
- }
- }
[java] view plaincopy
- public abstract class Bridge {
- private Sourceable source;
- public void method(){
- source.method();
- }
- public Sourceable getSource() {
- return source;
- }
- public void setSource(Sourceable source) {
- this.source = source;
- }
- }
[java] view plaincopy
- public class MyBridge extends Bridge {
- public void method(){
- getSource().method();
- }
- }
[java] view plaincopy
- public class BridgeTest {
- public static void main(String[] args) {
- Bridge bridge = new MyBridge();
- /*调用第一个对象*/
- Sourceable source1 = new SourceSub1();
- bridge.setSource(source1);
- bridge.method();
- /*调用第二个对象*/
- Sourceable source2 = new SourceSub2();
- bridge.setSource(source2);
- bridge.method();
- }
- }
this is the second sub!

11、组合模式(Composite)

[java] view plaincopy
- public class TreeNode {
- private String name;
- private TreeNode parent;
- private Vector<TreeNode> children = new Vector<TreeNode>();
- public TreeNode(String name){
- this.name = name;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public TreeNode getParent() {
- return parent;
- }
- public void setParent(TreeNode parent) {
- this.parent = parent;
- }
- //添加孩子节点
- public void add(TreeNode node){
- children.add(node);
- }
- //删除孩子节点
- public void remove(TreeNode node){
- children.remove(node);
- }
- //取得孩子节点
- public Enumeration<TreeNode> getChildren(){
- return children.elements();
- }
- }
[java] view plaincopy
- public class Tree {
- TreeNode root = null;
- public Tree(String name) {
- root = new TreeNode(name);
- }
- public static void main(String[] args) {
- Tree tree = new Tree("A");
- TreeNode nodeB = new TreeNode("B");
- TreeNode nodeC = new TreeNode("C");
- nodeB.add(nodeC);
- tree.root.add(nodeB);
- System.out.println("build the tree finished!");
- }
- }


[java] view plaincopy
- public class ConnectionPool {
- private Vector<Connection> pool;
- /*公有属性*/
- private String url = "jdbc:mysql://localhost:3306/test";
- private String username = "root";
- private String password = "root";
- private String driverClassName = "com.mysql.jdbc.Driver";
- private int poolSize = 100;
- private static ConnectionPool instance = null;
- Connection conn = null;
- /*构造方法,做一些初始化工作*/
- private ConnectionPool() {
- pool = new Vector<Connection>(poolSize);
- for (int i = 0; i < poolSize; i++) {
- try {
- Class.forName(driverClassName);
- conn = DriverManager.getConnection(url, username, password);
- pool.add(conn);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- /* 返回连接到连接池 */
- public synchronized void release() {
- pool.add(conn);
- }
- /* 返回连接池中的一个数据库连接 */
- public synchronized Connection getConnection() {
- if (pool.size() > 0) {
- Connection conn = pool.get(0);
- pool.remove(conn);
- return conn;
- } else {
- return null;
- }
- }
- }
通过连接池的管理,实现了数据库连接的共享,不需要每一次都重新创建连接,节省了数据库重新创建的开销,提升了系统的性能!
C、关系模式(11种)

父类与子类关系13、策略模式(strategy)

AbstractCalculator是辅助类,提供辅助方法,接下来,依次实现下每个类:
[java] view plaincopy
- public interface ICalculator {
- public int calculate(String exp);
- }
[java] view plaincopy
- public abstract class AbstractCalculator {
- public int[] split(String exp,String opt){
- String array[] = exp.split(opt);
- int arrayInt[] = new int[2];
- arrayInt[0] = Integer.parseInt(array[0]);
- arrayInt[1] = Integer.parseInt(array[1]);
- return arrayInt;
- }
- }
[java] view plaincopy
- public class Plus extends AbstractCalculator implements ICalculator {
- @Override
- public int calculate(String exp) {
- int arrayInt[] = split(exp,"\\+");
- return arrayInt[0]+arrayInt[1];
- }
- }
[java] view plaincopy
- public class Minus extends AbstractCalculator implements ICalculator {
- @Override
- public int calculate(String exp) {
- int arrayInt[] = split(exp,"-");
- return arrayInt[0]-arrayInt[1];
- }
- }
[java] view plaincopy
- public class Multiply extends AbstractCalculator implements ICalculator {
- @Override
- public int calculate(String exp) {
- int arrayInt[] = split(exp,"\\*");
- return arrayInt[0]*arrayInt[1];
- }
- }
[java] view plaincopy
- public class StrategyTest {
- public static void main(String[] args) {
- String exp = "2+8";
- ICalculator cal = new Plus();
- int result = cal.calculate(exp);
- System.out.println(result);
- }
- }
14、模板方法模式(Template Method)

[java] view plaincopy
- public abstract class AbstractCalculator {
- /*主方法,实现对本类其它方法的调用*/
- public final int calculate(String exp,String opt){
- int array[] = split(exp,opt);
- return calculate(array[0],array[1]);
- }
- /*被子类重写的方法*/
- abstract public int calculate(int num1,int num2);
- public int[] split(String exp,String opt){
- String array[] = exp.split(opt);
- int arrayInt[] = new int[2];
- arrayInt[0] = Integer.parseInt(array[0]);
- arrayInt[1] = Integer.parseInt(array[1]);
- return arrayInt;
- }
- }
[java] view plaincopy
- public class Plus extends AbstractCalculator {
- @Override
- public int calculate(int num1,int num2) {
- return num1 + num2;
- }
- }
[java] view plaincopy
- public class StrategyTest {
- public static void main(String[] args) {
- String exp = "8+8";
- AbstractCalculator cal = new Plus();
- int result = cal.calculate(exp, "\\+");
- System.out.println(result);
- }
- }
类之间的关系15、观察者模式(Observer)

[java] view plaincopy
- public interface Observer {
- public void update();
- }
[java] view plaincopy
- public class Observer1 implements Observer {
- @Override
- public void update() {
- System.out.println("observer1 has received!");
- }
- }
[java] view plaincopy
- public class Observer2 implements Observer {
- @Override
- public void update() {
- System.out.println("observer2 has received!");
- }
- }
[java] view plaincopy
- public interface Subject {
- /*增加观察者*/
- public void add(Observer observer);
- /*删除观察者*/
- public void del(Observer observer);
- /*通知所有的观察者*/
- public void notifyObservers();
- /*自身的操作*/
- public void operation();
- }
[java] view plaincopy
- public abstract class AbstractSubject implements Subject {
- private Vector<Observer> vector = new Vector<Observer>();
- @Override
- public void add(Observer observer) {
- vector.add(observer);
- }
- @Override
- public void del(Observer observer) {
- vector.remove(observer);
- }
- @Override
- public void notifyObservers() {
- Enumeration<Observer> enumo = vector.elements();
- while(enumo.hasMoreElements()){
- enumo.nextElement().update();
- }
- }
- }
[java] view plaincopy
- public class MySubject extends AbstractSubject {
- @Override
- public void operation() {
- System.out.println("update self!");
- notifyObservers();
- }
- }
测试类:
[java] view plaincopy
- public class ObserverTest {
- public static void main(String[] args) {
- Subject sub = new MySubject();
- sub.add(new Observer1());
- sub.add(new Observer2());
- sub.operation();
- }
- }
observer1 has received!
observer2 has received!
16、迭代子模式(Iterator)

[java] view plaincopy
- public interface Collection {
- public Iterator iterator();
- /*取得集合元素*/
- public Object get(int i);
- /*取得集合大小*/
- public int size();
- }
[java] view plaincopy
- public interface Iterator {
- //前移
- public Object previous();
- //后移
- public Object next();
- public boolean hasNext();
- //取得第一个元素
- public Object first();
- }
[java] view plaincopy
- public class MyCollection implements Collection {
- public String string[] = {"A","B","C","D","E"};
- @Override
- public Iterator iterator() {
- return new MyIterator(this);
- }
- @Override
- public Object get(int i) {
- return string;
- }
- @Override
- public int size() {
- return string.length;
- }
- }
[java] view plaincopy
- public class MyIterator implements Iterator {
- private Collection collection;
- private int pos = -1;
- public MyIterator(Collection collection){
- this.collection = collection;
- }
- @Override
- public Object previous() {
- if(pos > 0){
- pos--;
- }
- return collection.get(pos);
- }
- @Override
- public Object next() {
- if(pos<collection.size()-1){
- pos++;
- }
- return collection.get(pos);
- }
- @Override
- public boolean hasNext() {
- if(pos<collection.size()-1){
- return true;
- }else{
- return false;
- }
- }
- @Override
- public Object first() {
- pos = 0;
- return collection.get(pos);
- }
- }
[java] view plaincopy
- public class Test {
- public static void main(String[] args) {
- Collection collection = new MyCollection();
- Iterator it = collection.iterator();
- while(it.hasNext()){
- System.out.println(it.next());
- }
- }
- }
17、责任链模式(Chain of Responsibility)接下来我们将要谈谈责任链模式,有多个对象,每个对象持有对下一个对象的引用,这样就会形成一条链,请求在这条链上传递,直到某一对象决定处理该请求。但是发出者并不清楚到底最终那个对象会处理该请求,所以,责任链模式可以实现,在隐瞒客户端的情况下,对系统进行动态的调整。先看看关系图:

[java] view plaincopy
- public interface Handler {
- public void operator();
- }
[java] view plaincopy
- public abstract class AbstractHandler {
- private Handler handler;
- public Handler getHandler() {
- return handler;
- }
- public void setHandler(Handler handler) {
- this.handler = handler;
- }
- }
[java] view plaincopy
- public class MyHandler extends AbstractHandler implements Handler {
- private String name;
- public MyHandler(String name) {
- this.name = name;
- }
- @Override
- public void operator() {
- System.out.println(name+"deal!");
- if(getHandler()!=null){
- getHandler().operator();
- }
- }
- }
[java] view plaincopy
- public class Test {
- public static void main(String[] args) {
- MyHandler h1 = new MyHandler("h1");
- MyHandler h2 = new MyHandler("h2");
- MyHandler h3 = new MyHandler("h3");
- h1.setHandler(h2);
- h2.setHandler(h3);
- h1.operator();
- }
- }
h2deal!
h3deal!
18、命令模式(Command)

[java] view plaincopy
- public interface Command {
- public void exe();
- }
[java] view plaincopy
- public class MyCommand implements Command {
- private Receiver receiver;
- public MyCommand(Receiver receiver) {
- this.receiver = receiver;
- }
- @Override
- public void exe() {
- receiver.action();
- }
- }
[java] view plaincopy
- public class Receiver {
- public void action(){
- System.out.println("command received!");
- }
- }
[java] view plaincopy
- public class Invoker {
- private Command command;
- public Invoker(Command command) {
- this.command = command;
- }
- public void action(){
- command.exe();
- }
- }
[java] view plaincopy
- public class Test {
- public static void main(String[] args) {
- Receiver receiver = new Receiver();
- Command cmd = new MyCommand(receiver);
- Invoker invoker = new Invoker(cmd);
- invoker.action();
- }
- }

类的状态19、备忘录模式(Memento)

[java] view plaincopy
- public class Original {
- private String value;
- public String getValue() {
- return value;
- }
- public void setValue(String value) {
- this.value = value;
- }
- public Original(String value) {
- this.value = value;
- }
- public Memento createMemento(){
- return new Memento(value);
- }
- public void restoreMemento(Memento memento){
- this.value = memento.getValue();
- }
- }
[java] view plaincopy
- public class Memento {
- private String value;
- public Memento(String value) {
- this.value = value;
- }
- public String getValue() {
- return value;
- }
- public void setValue(String value) {
- this.value = value;
- }
- }
[java] view plaincopy
- 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;
- }
- }
[java] view plaincopy
- public class Test {
- public static void main(String[] args) {
- // 创建原始类
- Original origi = new Original("egg");
- // 创建备忘录
- Storage storage = new Storage(origi.createMemento());
- // 修改原始类的状态
- System.out.println("初始化状态为:" + origi.getValue());
- origi.setValue("niu");
- System.out.println("修改后的状态为:" + origi.getValue());
- // 回复原始类的状态
- origi.restoreMemento(storage.getMemento());
- System.out.println("恢复后的状态为:" + origi.getValue());
- }
- }
修改后的状态为:niu
恢复后的状态为:egg
20、状态模式(State)

[java] view plaincopy
- package com.xtfggef.dp.state;
- /**
- * 状态类的核心类
- * 2012-12-1
- * @author erqing
- *
- */
- public class State {
- private String value;
- public String getValue() {
- return value;
- }
- public void setValue(String value) {
- this.value = value;
- }
- public void method1(){
- System.out.println("execute the first opt!");
- }
- public void method2(){
- System.out.println("execute the second opt!");
- }
- }
[java] view plaincopy
- package com.xtfggef.dp.state;
- /**
- * 状态模式的切换类 2012-12-1
- * @author erqing
- *
- */
- 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 method() {
- if (state.getValue().equals("state1")) {
- state.method1();
- } else if (state.getValue().equals("state2")) {
- state.method2();
- }
- }
- }
测试类:[java] view plaincopy
- public class Test {
- public static void main(String[] args) {
- State state = new State();
- Context context = new Context(state);
- //设置第一种状态
- state.setValue("state1");
- context.method();
- //设置第二种状态
- state.setValue("state2");
- context.method();
- }
- }
输出:
execute the second opt!
通过中间类21、访问者模式(Visitor)

[java] view plaincopy
- public interface Visitor {
- public void visit(Subject sub);
- }
[java] view plaincopy
- public class MyVisitor implements Visitor {
- @Override
- public void visit(Subject sub) {
- System.out.println("visit the subject:"+sub.getSubject());
- }
- }
Subject类,accept方法,接受将要访问它的对象,getSubject()获取将要被访问的属性,
[java] view plaincopy
- public interface Subject {
- public void accept(Visitor visitor);
- public String getSubject();
- }
[java] view plaincopy
- public class MySubject implements Subject {
- @Override
- public void accept(Visitor visitor) {
- visitor.visit(this);
- }
- @Override
- public String getSubject() {
- return "love";
- }
- }
测试:[java] view plaincopy
- public class Test {
- public static void main(String[] args) {
- Visitor visitor = new MyVisitor();
- Subject sub = new MySubject();
- sub.accept(visitor);
- }
- }
输出:visit the subject:love
22、中介者模式(Mediator)

[java] view plaincopy
- public interface Mediator {
- public void createMediator();
- public void workAll();
- }
[java] view plaincopy
- public class MyMediator implements Mediator {
- private User user1;
- private User user2;
- public User getUser1() {
- return user1;
- }
- public User getUser2() {
- return user2;
- }
- @Override
- public void createMediator() {
- user1 = new User1(this);
- user2 = new User2(this);
- }
- @Override
- public void workAll() {
- user1.work();
- user2.work();
- }
- }
[java] view plaincopy
- public abstract class User {
- private Mediator mediator;
- public Mediator getMediator(){
- return mediator;
- }
- public User(Mediator mediator) {
- this.mediator = mediator;
- }
- public abstract void work();
- }
[java] view plaincopy
- public class User1 extends User {
- public User1(Mediator mediator){
- super(mediator);
- }
- @Override
- public void work() {
- System.out.println("user1 exe!");
- }
- }
[java] view plaincopy
- public class User2 extends User {
- public User2(Mediator mediator){
- super(mediator);
- }
- @Override
- public void work() {
- System.out.println("user2 exe!");
- }
- }
测试类:[java] view plaincopy
- public class Test {
- public static void main(String[] args) {
- Mediator mediator = new MyMediator();
- mediator.createMediator();
- mediator.workAll();
- }
- }
输出:
user2 exe!
23、解释器模式(Interpreter)解释器模式是我们暂时的最后一讲,一般主要应用在OOP开发中的编译器的开发中,所以适用面比较窄。

[java] view plaincopy
- public interface Expression {
- public int interpret(Context context);
- }
[java] view plaincopy
- public class Plus implements Expression {
- @Override
- public int interpret(Context context) {
- return context.getNum1()+context.getNum2();
- }
- }
[java] view plaincopy
- public class Minus implements Expression {
- @Override
- public int interpret(Context context) {
- return context.getNum1()-context.getNum2();
- }
- }
[java] view plaincopy
- 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;
- }
- }
[java] view plaincopy
- public class Test {
- public static void main(String[] args) {
- // 计算9+2-8的值
- int result = new Minus().interpret((new Context(new Plus()
- .interpret(new Context(9, 2)), 8)));
- System.out.println(result);
- }
- }
最后输出正确的结果:3。