![](http://dl.iteye.com/upload/attachment/0083/1180/421a1a3f-6777-3bca-85d7-00fc60c1ae8b.png)
- public interface Sender {
- public void Send();
- }
- public class MailSender implements Sender {
- @Override
- public void Send() {
- System.out.println("this is mailsender!");
- }
- }
- public class SmsSender implements Sender {
- @Override
- public void Send() {
- System.out.println("this is sms sender!");
- }
- }
- 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();
- }
- }
![点击查看原始大小图片](http://dl.iteye.com/upload/attachment/0083/1181/84673ccf-ef89-3774-b5cf-6d2523cd03e5.jpg)
public Sender produceMail(){
- return new MailSender();
- }
- public Sender produceSms(){
- return new SmsSender();
- }
- }
- public class FactoryTest {
- public static void main(String[] args) {
- SendFactory factory = new SendFactory();
- Sender sender = factory.produceMail();
- sender.Send();
- }
- }
- public class SendFactory {
- public static Sender produceMail(){
- return new MailSender();
- }
- public static Sender produceSms(){
- return new SmsSender();
- }
- }
- public class FactoryTest {
- public static void main(String[] args) {
- Sender sender = SendFactory.produceMail();
- sender.Send();
- }
- }
![点击查看原始大小图片](http://dl.iteye.com/upload/attachment/0083/1185/34a0f8de-16e0-3cd5-9f69-257fcb2be742.jpg)
- public interface Sender {
- public void Send();
- }
- public class MailSender implements Sender {
- @Override
- public void Send() {
- System.out.println("this is mailsender!");
- }
- }
- public class SmsSender implements Sender {
- @Override
- public void Send() {
- System.out.println("this is sms sender!");
- }
- }
- public class SendMailFactory implements Provider {
- @Override
- public Sender produce(){
- return new MailSender();
- }
- }
- public class SendSmsFactory implements Provider{
- @Override
- public Sender produce() {
- return new SmsSender();
- }
- }
- public interface Provider {
- public Sender produce();
- }
- public class Test {
- public static void main(String[] args) {
- Provider provider = new SendMailFactory();
- Sender sender = provider.produce();
- sender.Send();
- }
- }
- 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关键字,如下:
- public static synchronized Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- public static Singleton getInstance() {
- if (instance == null) {
- synchronized (instance) {
- if (instance == null) {
- instance = new Singleton();
- }
- }
- }
- return instance;
- }
- private static class SingletonFactory{
- private static Singleton instance = new Singleton();
- }
- public static Singleton getInstance(){
- return SingletonFactory.instance;
- }
- 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();
- }
- }
- 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;
- }
- }
- 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();
- }
- }
- public class Builder {
- private List<Sender> list = new ArrayList<Sender>();
- public void produceMailSender(int count){
- for(int i=0; i<count; i++){
- list.add(new MailSender());
- }
- }
- public void produceSmsSender(int count){
- for(int i=0; i<count; i++){
- list.add(new SmsSender());
- }
- }
- }
- public class Test {
- public static void main(String[] args) {
- Builder builder = new Builder();
- builder.produceMailSender(10);
- }
- }
- public class Prototype implements Cloneable {
- public Object clone() throws CloneNotSupportedException {
- Prototype proto = (Prototype) super.clone();
- return proto;
- }
- }
- 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;
- }
要实现深复制,需要采用流的形式读入当前对象的二进制输入,再写出二进制数据对应的对象。
![点击查看原始大小图片](http://dl.iteye.com/upload/attachment/0083/1187/e28698b9-994e-3fa8-8810-16f30e7cf3e3.jpg)
![](http://dl.iteye.com/upload/attachment/0083/1189/6b2d13aa-7cc7-3e98-9764-bdcb2c64f795.jpg)
- public class Source {
- public void method1() {
- System.out.println("this is original method!");
- }
- }
- public interface Targetable {
- /* 与原类中的方法相同 */
- public void method1();
- /* 新类的方法 */
- public void method2();
- }
- public class Adapter extends Source implements Targetable {
- @Override
- public void method2() {
- System.out.println("this is the targetable method!");
- }
- }
- public class AdapterTest {
- public static void main(String[] args) {
- Targetable target = new Adapter();
- target.method1();
- target.method2();
- }
- }
this is the targetable method!
![](http://dl.iteye.com/upload/attachment/0083/1191/0aabe35b-5b79-3ead-838f-9d4b6fbd774d.jpg)
- 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();
- }
- }
- public class AdapterTest {
- public static void main(String[] args) {
- Source source = new Source();
- Targetable target = new Wrapper(source);
- target.method1();
- target.method2();
- }
- }
![](http://dl.iteye.com/upload/attachment/0083/1193/a604fca8-e0c6-3e4e-b00a-49da21595b4e.jpg)
- public interface Sourceable {
- public void method1();
- public void method2();
- }
- public abstract class Wrapper2 implements Sourceable{
- public void method1(){}
- public void method2(){}
- }
- public class SourceSub1 extends Wrapper2 {
- public void method1(){
- System.out.println("the sourceable interface's first Sub1!");
- }
- }
- public class SourceSub2 extends Wrapper2 {
- public void method2(){
- System.out.println("the sourceable interface's second Sub2!");
- }
- }
- 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!
![](http://dl.iteye.com/upload/attachment/0083/1195/e1b8b6a3-0150-31ae-8f77-7c3d888b6f80.jpg)
- public interface Sourceable {
- public void method();
- }
- public class Source implements Sourceable {
- @Override
- public void method() {
- System.out.println("the original method!");
- }
- }
- 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!");
- }
- }
- 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!
![](http://dl.iteye.com/upload/attachment/0083/1197/ea094ad9-efc5-337d-a8e8-ce9223511144.jpg)
- public interface Sourceable {
- public void method();
- }
- public class Source implements Sourceable {
- @Override
- public void method() {
- System.out.println("the original method!");
- }
- }
- 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!");
- }
- }
- public class ProxyTest {
- public static void main(String[] args) {
- Sourceable source = new Proxy();
- source.method();
- }
- }
the original method!
after proxy!
![](http://dl.iteye.com/upload/attachment/0083/1199/eebe2103-6ced-35f2-8664-3a2e8a557f81.jpg)
- public class CPU {
- public void startup(){
- System.out.println("cpu startup!");
- }
- public void shutdown(){
- System.out.println("cpu shutdown!");
- }
- }
- public class Memory {
- public void startup(){
- System.out.println("memory startup!");
- }
- public void shutdown(){
- System.out.println("memory shutdown!");
- }
- }
- public class Disk {
- public void startup(){
- System.out.println("disk startup!");
- }
- public void shutdown(){
- System.out.println("disk shutdown!");
- }
- }
- 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!");
- }
- }
- 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!
![](http://dl.iteye.com/upload/attachment/0083/1201/35f0b172-b976-3757-bb51-c65d5c9ce68e.jpg)
- public interface Sourceable {
- public void method();
- }
- public class SourceSub1 implements Sourceable {
- @Override
- public void method() {
- System.out.println("this is the first sub!");
- }
- }
- public class SourceSub2 implements Sourceable {
- @Override
- public void method() {
- System.out.println("this is the second sub!");
- }
- }
- 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;
- }
- }
- public class MyBridge extends Bridge {
- public void method(){
- getSource().method();
- }
- }
- 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!
![](http://dl.iteye.com/upload/attachment/0083/1203/6f713d07-1409-3312-99c9-fa6b0909f0b2.jpg)
![](http://dl.iteye.com/upload/attachment/0083/1205/09cab656-5ff9-380e-9df1-326339ac3509.jpg)
- 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();
- }
- }
- 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!");
- }
- }
![](http://dl.iteye.com/upload/attachment/0083/1207/f7aae0dd-b250-3829-bb07-49d87069bfbb.jpg)
![](http://dl.iteye.com/upload/attachment/0083/1209/53bc0bf4-cafb-3a12-8574-e20a525f2b72.jpg)
- 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;
- }
- }
- }
通过连接池的管理,实现了数据库连接的共享,不需要每一次都重新创建连接,节省了数据库重新创建的开销,提升了系统的性能!本章讲解了7种结构型模式,因为篇幅的问题,剩下的11种行为型模式,
![](http://dl.iteye.com/upload/attachment/0083/1211/5e2feb58-4170-3c07-a370-ed99bdcab223.jpg)
![](http://dl.iteye.com/upload/attachment/0083/1213/2319a2c3-7ebd-3ee3-b389-1548074ea9c6.jpg)
AbstractCalculator是辅助类,提供辅助方法,接下来,依次实现下每个类:
- public interface ICalculator {
- public int calculate(String exp);
- }
- 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;
- }
- }
- public class Plus extends AbstractCalculator implements ICalculator {
- @Override
- public int calculate(String exp) {
- int arrayInt[] = split(exp,"\\+");
- return arrayInt[0]+arrayInt[1];
- }
- }
- public class Minus extends AbstractCalculator implements ICalculator {
- @Override
- public int calculate(String exp) {
- int arrayInt[] = split(exp,"-");
- return arrayInt[0]-arrayInt[1];
- }
- }
- public class Multiply extends AbstractCalculator implements ICalculator {
- @Override
- public int calculate(String exp) {
- int arrayInt[] = split(exp,"\\*");
- return arrayInt[0]*arrayInt[1];
- }
- }
- 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);
- }
- }
![](http://dl.iteye.com/upload/attachment/0083/1215/c3d57775-ddf9-302b-9dfe-c65967518d3c.jpg)
- 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;
- }
- }
- public class Plus extends AbstractCalculator {
- @Override
- public int calculate(int num1,int num2) {
- return num1 + num2;
- }
- }
- 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);
- }
- }
![](http://dl.iteye.com/upload/attachment/0083/1233/d588525c-fbad-3040-971c-69b2716c67a4.jpg)
- public interface Observer {
- public void update();
- }
- public class Observer1 implements Observer {
- @Override
- public void update() {
- System.out.println("observer1 has received!");
- }
- }
- public class Observer2 implements Observer {
- @Override
- public void update() {
- System.out.println("observer2 has received!");
- }
- }
- public interface Subject {
- /*增加观察者*/
- public void add(Observer observer);
- /*删除观察者*/
- public void del(Observer observer);
- /*通知所有的观察者*/
- public void notifyObservers();
- /*自身的操作*/
- public void operation();
- }
- 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();
- }
- }
- }
- public class MySubject extends AbstractSubject {
- @Override
- public void operation() {
- System.out.println("update self!");
- notifyObservers();
- }
- }
测试类:
- public class ObserverTest {
- public static void main(String[] args) {
- Subject sub = new MySubject();
- sub.add(new Observer1());
- sub.add(new Observer2());
- sub.operation();
- }
- }
输出:
update self!
observer1 has received!
observer2 has received!
这些东西,其实不难,只是有些抽象,不太容易整体理解,建议读者:根据关系图,新建项目,自己写代码(或者参考我的代码),按照总体思路走一遍,这样才能体会它的思想,理解起来容易!
16、迭代子模式(Iterator)
顾名思义,迭代器模式就是顺序访问聚集中的对象,一般来说,集合中非常常见,如果对集合类比较熟悉的话,理解本模式会十分轻松。这句话包含两层意思:一是需要遍历的对象,即聚集对象,二是迭代器对象,用于对聚集对象进行遍历访问。我们看下关系图:
这个思路和我们常用的一模一样,MyCollection中定义了集合的一些操作,MyIterator中定义了一系列迭代操作,且持有Collection实例,我们来看看实现代码:
两个接口:
- public interface Collection {
- public Iterator iterator();
- /*取得集合元素*/
- public Object get(int i);
- /*取得集合大小*/
- public int size();
- }
- public interface Iterator {
- //前移
- public Object previous();
- //后移
- public Object next();
- public boolean hasNext();
- //取得第一个元素
- public Object first();
- }
两个实现:
- 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[i];
- }
- @Override
- public int size() {
- return string.length;
- }
- }
- 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);
- }
- }
测试类:
- 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());
- }
- }
- }
输出:A B C D E
此处我们貌似模拟了一个集合类的过程,感觉是不是很爽?其实JDK中各个类也都是这些基本的东西,加一些设计模式,再加一些优化放到一起的,只要我们把这些东西学会了,掌握好了,我们也可以写出自己的集合类,甚至框架!
17、责任链模式(Chain of Responsibility)
接下来我们将要谈谈责任链模式,有多个对象,每个对象持有对下一个对象的引用,这样就会形成一条链,请求在这条链上传递,直到某一对象决定处理该请求。但是发出者并不清楚到底最终那个对象会处理该请求,所以,责任链模式可以实现,在隐瞒客户端的情况下,对系统进行动态的调整。先看看关系图:
Abstracthandler类提供了get和set方法,方便MyHandle类设置和修改引用对象,MyHandle类是核心,实例化后生成一系列相互持有的对象,构成一条链。
[java] view plaincopy- public interface Handler {
- public void operator();
- }
- public abstract class AbstractHandler {
- private Handler handler;
- public Handler getHandler() {
- return handler;
- }
- public void setHandler(Handler handler) {
- this.handler = handler;
- }
- }
- 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();
- }
- }
- }
- 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();
- }
- }
输出:
h1deal!
h2deal!
h3deal!
此处强调一点就是,链接上的请求可以是一条链,可以是一个树,还可以是一个环,模式本身不约束这个,需要我们自己去实现,同时,在一个时刻,命令只允许由一个对象传给另一个对象,而不允许传给多个对象。
18、命令模式(Command)
命令模式很好理解,举个例子,司令员下令让士兵去干件事情,从整个事情的角度来考虑,司令员的作用是,发出口令,口令经过传递,传到了士兵耳朵里,士兵去执行。这个过程好在,三者相互解耦,任何一方都不用去依赖其他人,只需要做好自己的事儿就行,司令员要的是结果,不会去关注到底士兵是怎么实现的。我们看看关系图:
Invoker是调用者(司令员),Receiver是被调用者(士兵),MyCommand是命令,实现了Command接口,持有接收对象,看实现代码:
- public interface Command {
- public void 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("command received!");
- }
- }
- public class Invoker {
- private Command command;
- public Invoker(Command command) {
- this.command = command;
- }
- public void action(){
- command.exe();
- }
- }
- 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();
- }
- }
输出:command received!
这个很哈理解,命令模式的目的就是达到命令的发出者和执行者之间解耦,实现请求和执行分开,熟悉Struts的同学应该知道,Struts其实就是一种将请求和呈现分离的技术,其中必然涉及命令模式的思想!
其实每个设计模式都是很重要的一种思想,看上去很熟,其实是因为我们在学到的东西中都有涉及,尽管有时我们并不知道,其实在Java本身的设计之中处处都有体现,像AWT、JDBC、集合类、IO管道或者是Web框架,里面设计模式无处不在。因为我们篇幅有限,很难讲每一个设计模式都讲的很详细,不过我会尽我所能,尽量在有限的空间和篇幅内,把意思写清楚了,更好让大家明白。本章不出意外的话,应该是设计模式最后一讲了,首先还是上一下上篇开头的那个图:
本章讲讲第三类和第四类。
19、备忘录模式(Memento)
主要目的是保存一个对象的某个状态,以便在适当的时候恢复对象,个人觉得叫备份模式更形象些,通俗的讲下:假设有原始类A,A中有各种属性,A可以决定需要备份的属性,备忘录类B是用来存储A的一些内部状态,类C呢,就是一个用来存储备忘录的,且只能存储,不能修改等操作。做个图来分析一下:
Original类是原始类,里面有需要保存的属性value及创建一个备忘录类,用来保存value值。Memento类是备忘录类,Storage类是存储备忘录的类,持有Memento类的实例,该模式很好理解。直接看源码:
- 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();
- }
- }
- 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;
- }
- }
- 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 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());
- }
- }
输出:
初始化状态为:egg
修改后的状态为:niu
恢复后的状态为:egg
简单描述下:新建原始类时,value被初始化为egg,后经过修改,将value的值置为niu,最后倒数第二行进行恢复状态,结果成功恢复了。其实我觉得这个模式叫“备份-恢复”模式最形象。
20、状态模式(State)
核心思想就是:当对象的状态改变时,同时改变其行为,很好理解!就拿QQ来说,有几种状态,在线、隐身、忙碌等,每个状态对应不同的操作,而且你的好友也能看到你的状态,所以,状态模式就两点:1、可以通过改变状态来获得不同的行为。2、你的好友能同时看到你的变化。看图:
State类是个状态类,Context类可以实现切换,我们来看看代码:
- 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!");
- }
- }
- 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();
- }
- }
- }
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 first opt!
execute the second opt!
根据这个特性,状态模式在日常开发中用的挺多的,尤其是做网站的时候,我们有时希望根据对象的某一属性,区别开他们的一些功能,比如说简单的权限控制等。
21、访问者模式(Visitor)
访问者模式把数据结构和作用于结构上的操作解耦合,使得操作集合可相对自由地演化。访问者模式适用于数据结构相对稳定算法又易变化的系统。因为访问者模式使得算法操作增加变得容易。若系统数据结构对象易于变化,经常有新的数据对象增加进来,则不适合使用访问者模式。访问者模式的优点是增加操作很容易,因为增加操作意味着增加新的访问者。访问者模式将有关行为集中到一个访问者对象中,其改变不影响系统数据结构。其缺点就是增加新的数据结构很困难。—— From 百科
简单来说,访问者模式就是一种分离对象数据结构与行为的方法,通过这种分离,可达到为一个被访问者动态添加新的操作而无需做其它的修改的效果。简单关系图:
来看看原码:一个Visitor类,存放要访问的对象,
- public interface Visitor {
- public void visit(Subject sub);
- }
- public class MyVisitor implements Visitor {
- @Override
- public void visit(Subject sub) {
- System.out.println("visit the subject:"+sub.getSubject());
- }
- }
- public interface Subject {
- public void accept(Visitor visitor);
- public String getSubject();
- }
- public class MySubject implements Subject {
- @Override
- public void accept(Visitor visitor) {
- visitor.visit(this);
- }
- @Override
- public String getSubject() {
- return "love";
- }
- }
- public class Test {
- public static void main(String[] args) {
- Visitor visitor = new MyVisitor();
- Subject sub = new MySubject();
- sub.accept(visitor);
- }
- }
该模式适用场景:如果我们想为一个现有的类增加新功能,不得不考虑几个事情:1、新功能会不会与现有功能出现兼容性问题?2、以后会不会再需要添加?3、如果类不允许修改代码怎么办?面对这些问题,最好的解决方法就是使用访问者模式,访问者模式适用于数据结构相对稳定的系统,把数据结构和算法解耦,
22、中介者模式(Mediator)
中介者模式也是用来降低类类之间的耦合的,因为如果类类之间有依赖关系的话,不利于功能的拓展和维护,因为只要修改一个对象,其它关联的对象都得进行修改。如果使用中介者模式,只需关心和Mediator类的关系,具体类类之间的关系及调度交给Mediator就行,这有点像spring容器的作用。先看看图:
User类统一接口,User1和User2分别是不同的对象,二者之间有关联,如果不采用中介者模式,则需要二者相互持有引用,这样二者的耦合度很高,为了解耦,引入了Mediator类,提供统一接口,MyMediator为其实现类,里面持有User1和User2的实例,用来实现对User1和User2的控制。这样User1和User2两个对象相互独立,他们只需要保持好和Mediator之间的关系就行,剩下的全由MyMediator类来维护!基本实现:
- public interface Mediator {
- public void createMediator();
- public void workAll();
- }
- 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();
- }
- }
- public abstract class User {
- private Mediator mediator;
- public Mediator getMediator(){
- return 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 exe!");
- }
- }
- 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();
- }
- }
user1 exe!
user2 exe!
23、解释器模式(Interpreter)
解释器模式是我们暂时的最后一讲,一般主要应用在OOP开发中的编译器的开发中,所以适用面比较窄。
Context类是一个上下文环境类,Plus和Minus分别是用来计算的实现,代码如下:
- public interface Expression {
- public int interpret(Context context);
- }
- public class Plus implements Expression {
- @Override
- public int interpret(Context context) {
- return context.getNum1()+context.getNum2();
- }
- }
- public class Minus implements Expression {
- @Override
- public int interpret(Context context) {
- return context.getNum1()-context.getNum2();
- }
- }
- 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 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);
- }
- }