你的位置:首页 > 软件开发 > Java > Java开发中的23种设计模式(转)

Java开发中的23种设计模式(转)

发布时间:2016-05-29 16:00:17
设计模式(Design Patterns) —&mda ...

Java开发中的23种设计模式(转)

设计模式(Design Patterns)

                                  ——可复用面向对象软件的基础

设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。 毫无疑问,设计模式于己于他人于系统都是多赢的,设计模式使代码编制真正工程化,设计模式是软件工程的基石,如同大厦的一块块砖石一样。项目中合理的运用设计模式可以完美的解决很多问题,每种模式在现在中都有相应的原理来与之对应,每一个模式描述了一个在我们周围不断重复发生的问题,以及该问题的核心解决方案,这也是它能被广泛应用的原因。本章系Java之美[从菜鸟到高手演变]系列之设计模式,我们会以理论与实践相结合的方式来进行本章的学习,希望广大程序爱好者,学好设计模式,做一个优秀的软件工程师!

企业级项目实战(带源码)地址http://zz563143188.iteye.com/blog/1825168

23种模式java实现源码下载地址 http://pan.baidu.com/share/link?shareid=372668&uk=4076915866#dir/path=%2F%E5%AD%A6%E4%B9%A0%E6%96%87%E4%BB%B6 
  1. public interface Sender {  
  2.     public void Send();  
  3. }  
  1. public class MailSender implements Sender {  
  2.     @Override  
  3.     public void Send() {  
  4.         System.out.println("this is mailsender!");  
  5.     }  
  6. }  
  1. public class SmsSender implements Sender {  
  2.   
  3.     @Override  
  4.     public void Send() {  
  5.         System.out.println("this is sms sender!");  
  6.     }  
  7. }  
  1. public class SendFactory {  
  2.   
  3.     public Sender produce(String type) {  
  4.         if ("mail".equals(type)) {  
  5.             return new MailSender();  
  6.         } else if ("sms".equals(type)) {  
  7.             return new SmsSender();  
  8.         } else {  
  9.             System.out.println("请输入正确的类型!");  
  10.             return null;  
  11.         }  
  12.     }  
  13. }  
  1.         return new MailSender();  
  2.     }  
  3.       
  4.     public Sender produceSms(){  
  5.         return new SmsSender();  
  6.     }  
  7. }  
  1. public class FactoryTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         SendFactory factory = new SendFactory();  
  5.         Sender sender = factory.produceMail();  
  6.         sender.Send();  
  7.     }  
  8. }  
  1. public class SendFactory {  
  2.       
  3.     public static Sender produceMail(){  
  4.         return new MailSender();  
  5.     }  
  6.       
  7.     public static Sender produceSms(){  
  8.         return new SmsSender();  
  9.     }  
  10. }  
  1. public class FactoryTest {  
  2.   
  3.     public static void main(String[] args) {      
  4.         Sender sender = SendFactory.produceMail();  
  5.         sender.Send();  
  6.     }  
  7. }  
  1. public interface Sender {  
  2.     public void Send();  
  3. }  
  1. public class MailSender implements Sender {  
  2.     @Override  
  3.     public void Send() {  
  4.         System.out.println("this is mailsender!");  
  5.     }  
  6. }  
  1. public class SmsSender implements Sender {  
  2.   
  3.     @Override  
  4.     public void Send() {  
  5.         System.out.println("this is sms sender!");  
  6.     }  
  7. }  
  1. public class SendMailFactory implements Provider {  
  2.       
  3.     @Override  
  4.     public Sender produce(){  
  5.         return new MailSender();  
  6.     }  
  7. }  
  1. public class SendSmsFactory implements Provider{  
  2.   
  3.     @Override  
  4.     public Sender produce() {  
  5.         return new SmsSender();  
  6.     }  
  7. }  
  1. public interface Provider {  
  2.     public Sender produce();  
  3. }  
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Provider provider = new SendMailFactory();  
  5.         Sender sender = provider.produce();  
  6.         sender.Send();  
  7.     }  
  8. }  
  1. public class Singleton {  
  2.   
  3.     /* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */  
  4.     private static Singleton instance = null;  
  5.   
  6.     /* 私有构造方法,防止被实例化 */  
  7.     private Singleton() {  
  8.     }  
  9.   
  10.     /* 静态工程方法,创建实例 */  
  11.     public static Singleton getInstance() {  
  12.         if (instance == null) {  
  13.             instance = new Singleton();  
  14.         }  
  15.         return instance;  
  16.     }  
  17.   
  18.     /* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */  
  19.     public Object readResolve() {  
  20.         return instance;  
  21.     }  
  22. }  
  1. public static synchronized Singleton getInstance() {  
  2.         if (instance == null) {  
  3.             instance = new Singleton();  
  4.         }  
  5.         return instance;  
  6.     }  
  1. public static Singleton getInstance() {  
  2.         if (instance == null) {  
  3.             synchronized (instance) {  
  4.                 if (instance == null) {  
  5.                     instance = new Singleton();  
  6.                 }  
  7.             }  
  8.         }  
  9.         return instance;  
  10.     }  
  1. private static class SingletonFactory{           
  2.         private static Singleton instance = new Singleton();           
  3.     }           
  4.     public static Singleton getInstance(){           
  5.         return SingletonFactory.instance;           
  6.     }   
  1. public class Singleton {  
  2.   
  3.     /* 私有构造方法,防止被实例化 */  
  4.     private Singleton() {  
  5.     }  
  6.   
  7.     /* 此处使用一个内部类来维护单例 */  
  8.     private static class SingletonFactory {  
  9.         private static Singleton instance = new Singleton();  
  10.     }  
  11.   
  12.     /* 获取实例 */  
  13.     public static Singleton getInstance() {  
  14.         return SingletonFactory.instance;  
  15.     }  
  16.   
  17.     /* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */  
  18.     public Object readResolve() {  
  19.         return getInstance();  
  20.     }  
  21. }  
  1. public class SingletonTest {  
  2.   
  3.     private static SingletonTest instance = null;  
  4.   
  5.     private SingletonTest() {  
  6.     }  
  7.   
  8.     private static synchronized void syncInit() {  
  9.         if (instance == null) {  
  10.             instance = new SingletonTest();  
  11.         }  
  12.     }  
  13.   
  14.     public static SingletonTest getInstance() {  
  15.         if (instance == null) {  
  16.             syncInit();  
  17.         }  
  18.         return instance;  
  19.     }  
  20. }  
  1. public class SingletonTest {  
  2.   
  3.     private static SingletonTest instance = null;  
  4.     private Vector properties = null;  
  5.   
  6.     public Vector getProperties() {  
  7.         return properties;  
  8.     }  
  9.   
  10.     private SingletonTest() {  
  11.     }  
  12.   
  13.     private static synchronized void syncInit() {  
  14.         if (instance == null) {  
  15.             instance = new SingletonTest();  
  16.         }  
  17.     }  
  18.   
  19.     public static SingletonTest getInstance() {  
  20.         if (instance == null) {  
  21.             syncInit();  
  22.         }  
  23.         return instance;  
  24.     }  
  25.   
  26.     public void updateProperties() {  
  27.         SingletonTest shadow = new SingletonTest();  
  28.         properties = shadow.getProperties();  
  29.     }  
  30. }  
  1. public class Builder {  
  2.       
  3.     private List<Sender> list = new ArrayList<Sender>();  
  4.       
  5.     public void produceMailSender(int count){  
  6.         for(int i=0; i<count; i++){  
  7.             list.add(new MailSender());  
  8.         }  
  9.     }  
  10.       
  11.     public void produceSmsSender(int count){  
  12.         for(int i=0; i<count; i++){  
  13.             list.add(new SmsSender());  
  14.         }  
  15.     }  
  16. }  
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Builder builder = new Builder();  
  5.         builder.produceMailSender(10);  
  6.     }  
  7. }  
  1. public class Prototype implements Cloneable {  
  2.   
  3.     public Object clone() throws CloneNotSupportedException {  
  4.         Prototype proto = (Prototype) super.clone();  
  5.         return proto;  
  6.     }  
  7. }  
  1. public class Prototype implements Cloneable, Serializable {  
  2.   
  3.     private static final long serialVersionUID = 1L;  
  4.     private String string;  
  5.   
  6.     private SerializableObject obj;  
  7.   
  8.     /* 浅复制 */  
  9.     public Object clone() throws CloneNotSupportedException {  
  10.         Prototype proto = (Prototype) super.clone();  
  11.         return proto;  
  12.     }  
  13.   
  14.     /* 深复制 */  
  15.     public Object deepClone() throws IOException, ClassNotFoundException {  
  16.   
  17.         /* 写入当前对象的二进制流 */  
  18.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  19.         ObjectOutputStream oos = new ObjectOutputStream(bos);  
  20.         oos.writeObject(this);  
  21.   
  22.         /* 读出二进制流产生的新对象 */  
  23.         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());  
  24.         ObjectInputStream ois = new ObjectInputStream(bis);  
  25.         return ois.readObject();  
  26.     }  
  27.   
  28.     public String getString() {  
  29.         return string;  
  30.     }  
  31.   
  32.     public void setString(String string) {  
  33.         this.string = string;  
  34.     }  
  35.   
  36.     public SerializableObject getObj() {  
  37.         return obj;  
  38.     }  
  39.   
  40.     public void setObj(SerializableObject obj) {  
  41.         this.obj = obj;  
  42.     }  
  43.   
  44. }  
  45.   
  46. class SerializableObject implements Serializable {  
  47.     private static final long serialVersionUID = 1L;  
  48. }  
  1. public class Source {  
  2.   
  3.     public void method1() {  
  4.         System.out.println("this is original method!");  
  5.     }  
  6. }  
  1. public interface Targetable {  
  2.   
  3.     /* 与原类中的方法相同 */  
  4.     public void method1();  
  5.   
  6.     /* 新类的方法 */  
  7.     public void method2();  
  8. }  
  1. public class Adapter extends Source implements Targetable {  
  2.   
  3.     @Override  
  4.     public void method2() {  
  5.         System.out.println("this is the targetable method!");  
  6.     }  
  7. }  
  1. public class AdapterTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Targetable target = new Adapter();  
  5.         target.method1();  
  6.         target.method2();  
  7.     }  
  8. }  
  1. public class Wrapper implements Targetable {  
  2.   
  3.     private Source source;  
  4.       
  5.     public Wrapper(Source source){  
  6.         super();  
  7.         this.source = source;  
  8.     }  
  9.     @Override  
  10.     public void method2() {  
  11.         System.out.println("this is the targetable method!");  
  12.     }  
  13.   
  14.     @Override  
  15.     public void method1() {  
  16.         source.method1();  
  17.     }  
  18. }  
  1. public class AdapterTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Source source = new Source();  
  5.         Targetable target = new Wrapper(source);  
  6.         target.method1();  
  7.         target.method2();  
  8.     }  
  9. }  
  1. public interface Sourceable {  
  2.       
  3.     public void method1();  
  4.     public void method2();  
  5. }  
  1. public abstract class Wrapper2 implements Sourceable{  
  2.       
  3.     public void method1(){}  
  4.     public void method2(){}  
  5. }  
  1. public class SourceSub1 extends Wrapper2 {  
  2.     public void method1(){  
  3.         System.out.println("the sourceable interface's first Sub1!");  
  4.     }  
  5. }  
  1. public class SourceSub2 extends Wrapper2 {  
  2.     public void method2(){  
  3.         System.out.println("the sourceable interface's second Sub2!");  
  4.     }  
  5. }  
  1. public class WrapperTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Sourceable source1 = new SourceSub1();  
  5.         Sourceable source2 = new SourceSub2();  
  6.           
  7.         source1.method1();  
  8.         source1.method2();  
  9.         source2.method1();  
  10.         source2.method2();  
  11.     }  
  12. }  
  1. public interface Sourceable {  
  2.     public void method();  
  3. }  
  1. public class Source implements Sourceable {  
  2.   
  3.     @Override  
  4.     public void method() {  
  5.         System.out.println("the original method!");  
  6.     }  
  7. }  
  1. public class Decorator implements Sourceable {  
  2.   
  3.     private Sourceable source;  
  4.       
  5.     public Decorator(Sourceable source){  
  6.         super();  
  7.         this.source = source;  
  8.     }  
  9.     @Override  
  10.     public void method() {  
  11.         System.out.println("before decorator!");  
  12.         source.method();  
  13.         System.out.println("after decorator!");  
  14.     }  
  15. }  
  1. public class DecoratorTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Sourceable source = new Source();  
  5.         Sourceable obj = new Decorator(source);  
  6.         obj.method();  
  7.     }  
  8. }  
  1. public interface Sourceable {  
  2.     public void method();  
  3. }  
  1. public class Source implements Sourceable {  
  2.   
  3.     @Override  
  4.     public void method() {  
  5.         System.out.println("the original method!");  
  6.     }  
  7. }  
  1. public class Proxy implements Sourceable {  
  2.   
  3.     private Source source;  
  4.     public Proxy(){  
  5.         super();  
  6.         this.source = new Source();  
  7.     }  
  8.     @Override  
  9.     public void method() {  
  10.         before();  
  11.         source.method();  
  12.         atfer();  
  13.     }  
  14.     private void atfer() {  
  15.         System.out.println("after proxy!");  
  16.     }  
  17.     private void before() {  
  18.         System.out.println("before proxy!");  
  19.     }  
  20. }  
  1. public class ProxyTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Sourceable source = new Proxy();  
  5.         source.method();  
  6.     }  
  7.   
  8. }  
  1. public class CPU {  
  2.       
  3.     public void startup(){  
  4.         System.out.println("cpu startup!");  
  5.     }  
  6.       
  7.     public void shutdown(){  
  8.         System.out.println("cpu shutdown!");  
  9.     }  
  10. }  
  1. public class Memory {  
  2.       
  3.     public void startup(){  
  4.         System.out.println("memory startup!");  
  5.     }  
  6.       
  7.     public void shutdown(){  
  8.         System.out.println("memory shutdown!");  
  9.     }  
  10. }  
  1. public class Disk {  
  2.       
  3.     public void startup(){  
  4.         System.out.println("disk startup!");  
  5.     }  
  6.       
  7.     public void shutdown(){  
  8.         System.out.println("disk shutdown!");  
  9.     }  
  10. }  
  1. public class Computer {  
  2.     private CPU cpu;  
  3.     private Memory memory;  
  4.     private Disk disk;  
  5.       
  6.     public Computer(){  
  7.         cpu = new CPU();  
  8.         memory = new Memory();  
  9.         disk = new Disk();  
  10.     }  
  11.       
  12.     public void startup(){  
  13.         System.out.println("start the computer!");  
  14.         cpu.startup();  
  15.         memory.startup();  
  16.         disk.startup();  
  17.         System.out.println("start computer finished!");  
  18.     }  
  19.       
  20.     public void shutdown(){  
  21.         System.out.println("begin to close the computer!");  
  22.         cpu.shutdown();  
  23.         memory.shutdown();  
  24.         disk.shutdown();  
  25.         System.out.println("computer closed!");  
  26.     }  
  27. }  
  1. public class User {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Computer computer = new Computer();  
  5.         computer.startup();  
  6.         computer.shutdown();  
  7.     }  
  8. }  
  1. public interface Sourceable {  
  2.     public void method();  
  3. }  
  1. public class SourceSub1 implements Sourceable {  
  2.   
  3.     @Override  
  4.     public void method() {  
  5.         System.out.println("this is the first sub!");  
  6.     }  
  7. }  
  1. public class SourceSub2 implements Sourceable {  
  2.   
  3.     @Override  
  4.     public void method() {  
  5.         System.out.println("this is the second sub!");  
  6.     }  
  7. }  
  1. public abstract class Bridge {  
  2.     private Sourceable source;  
  3.   
  4.     public void method(){  
  5.         source.method();  
  6.     }  
  7.       
  8.     public Sourceable getSource() {  
  9.         return source;  
  10.     }  
  11.   
  12.     public void setSource(Sourceable source) {  
  13.         this.source = source;  
  14.     }  
  15. }  
  1. public class MyBridge extends Bridge {  
  2.     public void method(){  
  3.         getSource().method();  
  4.     }  
  5. }  
  1. public class BridgeTest {  
  2.       
  3.     public static void main(String[] args) {  
  4.           
  5.         Bridge bridge = new MyBridge();  
  6.           
  7.         /*调用第一个对象*/  
  8.         Sourceable source1 = new SourceSub1();  
  9.         bridge.setSource(source1);  
  10.         bridge.method();  
  11.           
  12.         /*调用第二个对象*/  
  13.         Sourceable source2 = new SourceSub2();  
  14.         bridge.setSource(source2);  
  15.         bridge.method();  
  16.     }  
  17. }  
  1. public class TreeNode {  
  2.       
  3.     private String name;  
  4.     private TreeNode parent;  
  5.     private Vector<TreeNode> children = new Vector<TreeNode>();  
  6.       
  7.     public TreeNode(String name){  
  8.         this.name = name;  
  9.     }  
  10.   
  11.     public String getName() {  
  12.         return name;  
  13.     }  
  14.   
  15.     public void setName(String name) {  
  16.         this.name = name;  
  17.     }  
  18.   
  19.     public TreeNode getParent() {  
  20.         return parent;  
  21.     }  
  22.   
  23.     public void setParent(TreeNode parent) {  
  24.         this.parent = parent;  
  25.     }  
  26.       
  27.     //添加孩子节点  
  28.     public void add(TreeNode node){  
  29.         children.add(node);  
  30.     }  
  31.       
  32.     //删除孩子节点  
  33.     public void remove(TreeNode node){  
  34.         children.remove(node);  
  35.     }  
  36.       
  37.     //取得孩子节点  
  38.     public Enumeration<TreeNode> getChildren(){  
  39.         return children.elements();  
  40.     }  
  41. }  
  1. public class Tree {  
  2.   
  3.     TreeNode root = null;  
  4.   
  5.     public Tree(String name) {  
  6.         root = new TreeNode(name);  
  7.     }  
  8.   
  9.     public static void main(String[] args) {  
  10.         Tree tree = new Tree("A");  
  11.         TreeNode nodeB = new TreeNode("B");  
  12.         TreeNode nodeC = new TreeNode("C");  
  13.           
  14.         nodeB.add(nodeC);  
  15.         tree.root.add(nodeB);  
  16.         System.out.println("build the tree finished!");  
  17.     }  
  18. }  
  1. public class ConnectionPool {  
  2.       
  3.     private Vector<Connection> pool;  
  4.       
  5.     /*公有属性*/  
  6.     private String url = "jdbc:mysql://localhost:3306/test";  
  7.     private String username = "root";  
  8.     private String password = "root";  
  9.     private String driverClassName = "com.mysql.jdbc.Driver";  
  10.   
  11.     private int poolSize = 100;  
  12.     private static ConnectionPool instance = null;  
  13.     Connection conn = null;  
  14.   
  15.     /*构造方法,做一些初始化工作*/  
  16.     private ConnectionPool() {  
  17.         pool = new Vector<Connection>(poolSize);  
  18.   
  19.         for (int i = 0; i < poolSize; i++) {  
  20.             try {  
  21.                 Class.forName(driverClassName);  
  22.                 conn = DriverManager.getConnection(url, username, password);  
  23.                 pool.add(conn);  
  24.             } catch (ClassNotFoundException e) {  
  25.                 e.printStackTrace();  
  26.             } catch (SQLException e) {  
  27.                 e.printStackTrace();  
  28.             }  
  29.         }  
  30.     }  
  31.   
  32.     /* 返回连接到连接池 */  
  33.     public synchronized void release() {  
  34.         pool.add(conn);  
  35.     }  
  36.   
  37.     /* 返回连接池中的一个数据库连接 */  
  38.     public synchronized Connection getConnection() {  
  39.         if (pool.size() > 0) {  
  40.             Connection conn = pool.get(0);  
  41.             pool.remove(conn);  
  42.             return conn;  
  43.         } else {  
  44.             return null;  
  45.         }  
  46.     }  
  47. }  

本章是关于设计模式的最后一讲,会讲到第三种设计模式——行为型模式,共11种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。这段时间一直在写关于设计模式的东西,终于写到一半了,写博文是个很费时间的东西,因为我得为读者负责,不论是图还是代码还是表述,都希望能尽量写清楚,以便读者理解,我想不论是我还是读者,都希望看到高质量的博文出来,从我本人出发,我会一直坚持下去,不断更新,源源动力来自于读者朋友们的不断支持,我会尽自己的努力,写好每一篇文章!希望大家能不断给出意见和建议,共同打造完美的博文!

 

 

先来张图,看看这11中模式的关系:

第一类:通过父类与子类的关系进行实现。第二类:两个类之间。第三类:类的状态。第四类:通过中间类

Java开发中的23种设计模式(转)

13、策略模式(strategy)

策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,属于辅助类),提供辅助函数,关系图如下:

Java开发中的23种设计模式(转)

图中ICalculator提供同意的方法,

  1. public interface ICalculator {  
  2.     public int calculate(String exp);  
  3. }  
  1. public abstract class AbstractCalculator {  
  2.       
  3.     public int[] split(String exp,String opt){  
  4.         String array[] = exp.split(opt);  
  5.         int arrayInt[] = new int[2];  
  6.         arrayInt[0] = Integer.parseInt(array[0]);  
  7.         arrayInt[1] = Integer.parseInt(array[1]);  
  8.         return arrayInt;  
  9.     }  
  10. }  
  1. public class Plus extends AbstractCalculator implements ICalculator {  
  2.   
  3.     @Override  
  4.     public int calculate(String exp) {  
  5.         int arrayInt[] = split(exp,"\\+");  
  6.         return arrayInt[0]+arrayInt[1];  
  7.     }  
  8. }  
  1. public class Minus extends AbstractCalculator implements ICalculator {  
  2.   
  3.     @Override  
  4.     public int calculate(String exp) {  
  5.         int arrayInt[] = split(exp,"-");  
  6.         return arrayInt[0]-arrayInt[1];  
  7.     }  
  8.   
  9. }  
  1. public class Multiply extends AbstractCalculator implements ICalculator {  
  2.   
  3.     @Override  
  4.     public int calculate(String exp) {  
  5.         int arrayInt[] = split(exp,"\\*");  
  6.         return arrayInt[0]*arrayInt[1];  
  7.     }  
  8. }  
  1. public class StrategyTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         String exp = "2+8";  
  5.         ICalculator cal = new Plus();  
  6.         int result = cal.calculate(exp);  
  7.         System.out.println(result);  
  8.     }  
  9. }  
  1. public abstract class AbstractCalculator {  
  2.       
  3.     /*主方法,实现对本类其它方法的调用*/  
  4.     public final int calculate(String exp,String opt){  
  5.         int array[] = split(exp,opt);  
  6.         return calculate(array[0],array[1]);  
  7.     }  
  8.       
  9.     /*被子类重写的方法*/  
  10.     abstract public int calculate(int num1,int num2);  
  11.       
  12.     public int[] split(String exp,String opt){  
  13.         String array[] = exp.split(opt);  
  14.         int arrayInt[] = new int[2];  
  15.         arrayInt[0] = Integer.parseInt(array[0]);  
  16.         arrayInt[1] = Integer.parseInt(array[1]);  
  17.         return arrayInt;  
  18.     }  
  19. }  
  1. public class Plus extends AbstractCalculator {  
  2.   
  3.     @Override  
  4.     public int calculate(int num1,int num2) {  
  5.         return num1 + num2;  
  6.     }  
  7. }  
  1. public class StrategyTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         String exp = "8+8";  
  5.         AbstractCalculator cal = new Plus();  
  6.         int result = cal.calculate(exp, "\\+");  
  7.         System.out.println(result);  
  8.     }  
  9. }  
  1. public interface Observer {  
  2.     public void update();  
  3. }  
  1. public class Observer1 implements Observer {  
  2.   
  3.     @Override  
  4.     public void update() {  
  5.         System.out.println("observer1 has received!");  
  6.     }  
  7. }  
  1. public class Observer2 implements Observer {  
  2.   
  3.     @Override  
  4.     public void update() {  
  5.         System.out.println("observer2 has received!");  
  6.     }  
  7.   
  8. }  
  1. public interface Subject {  
  2.       
  3.     /*增加观察者*/  
  4.     public void add(Observer observer);  
  5.       
  6.     /*删除观察者*/  
  7.     public void del(Observer observer);  
  8.       
  9.     /*通知所有的观察者*/  
  10.     public void notifyObservers();  
  11.       
  12.     /*自身的操作*/  
  13.     public void operation();  
  14. }  
  1. public abstract class AbstractSubject implements Subject {  
  2.   
  3.     private Vector<Observer> vector = new Vector<Observer>();  
  4.     @Override  
  5.     public void add(Observer observer) {  
  6.         vector.add(observer);  
  7.     }  
  8.   
  9.     @Override  
  10.     public void del(Observer observer) {  
  11.         vector.remove(observer);  
  12.     }  
  13.   
  14.     @Override  
  15.     public void notifyObservers() {  
  16.         Enumeration<Observer> enumo = vector.elements();  
  17.         while(enumo.hasMoreElements()){  
  18.             enumo.nextElement().update();  
  19.         }  
  20.     }  
  21. }  
  1. public class MySubject extends AbstractSubject {  
  2.   
  3.     @Override  
  4.     public void operation() {  
  5.         System.out.println("update self!");  
  6.         notifyObservers();  
  7.     }  
  8.   
  9. }  
  1. public class ObserverTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Subject sub = new MySubject();  
  5.         sub.add(new Observer1());  
  6.         sub.add(new Observer2());  
  7.           
  8.         sub.operation();  
  9.     }  
  10.   
  11. }  
  1. public interface Collection {  
  2.       
  3.     public Iterator iterator();  
  4.       
  5.     /*取得集合元素*/  
  6.     public Object get(int i);  
  7.       
  8.     /*取得集合大小*/  
  9.     public int size();  
  10. }  
  1. public interface Iterator {  
  2.     //前移  
  3.     public Object previous();  
  4.       
  5.     //后移  
  6.     public Object next();  
  7.     public boolean hasNext();  
  8.       
  9.     //取得第一个元素  
  10.     public Object first();  
  11. }  
  1. public class MyCollection implements Collection {  
  2.   
  3.     public String string[] = {"A","B","C","D","E"};  
  4.     @Override  
  5.     public Iterator iterator() {  
  6.         return new MyIterator(this);  
  7.     }  
  8.   
  9.     @Override  
  10.     public Object get(int i) {  
  11.         return string[i];  
  12.     }  
  13.   
  14.     @Override  
  15.     public int size() {  
  16.         return string.length;  
  17.     }  
  18. }  
  1. public class MyIterator implements Iterator {  
  2.   
  3.     private Collection collection;  
  4.     private int pos = -1;  
  5.       
  6.     public MyIterator(Collection collection){  
  7.         this.collection = collection;  
  8.     }  
  9.       
  10.     @Override  
  11.     public Object previous() {  
  12.         if(pos > 0){  
  13.             pos--;  
  14.         }  
  15.         return collection.get(pos);  
  16.     }  
  17.   
  18.     @Override  
  19.     public Object next() {  
  20.         if(pos<collection.size()-1){  
  21.             pos++;  
  22.         }  
  23.         return collection.get(pos);  
  24.     }  
  25.   
  26.     @Override  
  27.     public boolean hasNext() {  
  28.         if(pos<collection.size()-1){  
  29.             return true;  
  30.         }else{  
  31.             return false;  
  32.         }  
  33.     }  
  34.   
  35.     @Override  
  36.     public Object first() {  
  37.         pos = 0;  
  38.         return collection.get(pos);  
  39.     }  
  40.   
  41. }  
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Collection collection = new MyCollection();  
  5.         Iterator it = collection.iterator();  
  6.           
  7.         while(it.hasNext()){  
  8.             System.out.println(it.next());  
  9.         }  
  10.     }  
  11. }  
  1. public interface Handler {  
  2.     public void operator();  
  3. }  
  1. public abstract class AbstractHandler {  
  2.       
  3.     private Handler handler;  
  4.   
  5.     public Handler getHandler() {  
  6.         return handler;  
  7.     }  
  8.   
  9.     public void setHandler(Handler handler) {  
  10.         this.handler = handler;  
  11.     }  
  12.       
  13. }  
  1. public class MyHandler extends AbstractHandler implements Handler {  
  2.   
  3.     private String name;  
  4.   
  5.     public MyHandler(String name) {  
  6.         this.name = name;  
  7.     }  
  8.   
  9.     @Override  
  10.     public void operator() {  
  11.         System.out.println(name+"deal!");  
  12.         if(getHandler()!=null){  
  13.             getHandler().operator();  
  14.         }  
  15.     }  
  16. }  
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.         MyHandler h1 = new MyHandler("h1");  
  5.         MyHandler h2 = new MyHandler("h2");  
  6.         MyHandler h3 = new MyHandler("h3");  
  7.   
  8.         h1.setHandler(h2);  
  9.         h2.setHandler(h3);  
  10.   
  11.         h1.operator();  
  12.     }  
  13. }  
  1. public interface Command {  
  2.     public void exe();  
  3. }  
  1. public class MyCommand implements Command {  
  2.   
  3.     private Receiver receiver;  
  4.       
  5.     public MyCommand(Receiver receiver) {  
  6.         this.receiver = receiver;  
  7.     }  
  8.   
  9.     @Override  
  10.     public void exe() {  
  11.         receiver.action();  
  12.     }  
  13. }  
  1. public class Receiver {  
  2.     public void action(){  
  3.         System.out.println("command received!");  
  4.     }  
  5. }  
  1. public class Invoker {  
  2.       
  3.     private Command command;  
  4.       
  5.     public Invoker(Command command) {  
  6.         this.command = command;  
  7.     }  
  8.   
  9.     public void action(){  
  10.         command.exe();  
  11.     }  
  12. }  
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Receiver receiver = new Receiver();  
  5.         Command cmd = new MyCommand(receiver);  
  6.         Invoker invoker = new Invoker(cmd);  
  7.         invoker.action();  
  8.     }  
  9. }  
  1. public class Original {  
  2.       
  3.     private String value;  
  4.       
  5.     public String getValue() {  
  6.         return value;  
  7.     }  
  8.   
  9.     public void setValue(String value) {  
  10.         this.value = value;  
  11.     }  
  12.   
  13.     public Original(String value) {  
  14.         this.value = value;  
  15.     }  
  16.   
  17.     public Memento createMemento(){  
  18.         return new Memento(value);  
  19.     }  
  20.       
  21.     public void restoreMemento(Memento memento){  
  22.         this.value = memento.getValue();  
  23.     }  
  24. }  
  1. public class Memento {  
  2.       
  3.     private String value;  
  4.   
  5.     public Memento(String value) {  
  6.         this.value = value;  
  7.     }  
  8.   
  9.     public String getValue() {  
  10.         return value;  
  11.     }  
  12.   
  13.     public void setValue(String value) {  
  14.         this.value = value;  
  15.     }  
  16. }  
  1. public class Storage {  
  2.       
  3.     private Memento memento;  
  4.       
  5.     public Storage(Memento memento) {  
  6.         this.memento = memento;  
  7.     }  
  8.   
  9.     public Memento getMemento() {  
  10.         return memento;  
  11.     }  
  12.   
  13.     public void setMemento(Memento memento) {  
  14.         this.memento = memento;  
  15.     }  
  16. }  
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.           
  5.         // 创建原始类  
  6.         Original origi = new Original("egg");  
  7.   
  8.         // 创建备忘录  
  9.         Storage storage = new Storage(origi.createMemento());  
  10.   
  11.         // 修改原始类的状态  
  12.         System.out.println("初始化状态为:" + origi.getValue());  
  13.         origi.setValue("niu");  
  14.         System.out.println("修改后的状态为:" + origi.getValue());  
  15.   
  16.         // 回复原始类的状态  
  17.         origi.restoreMemento(storage.getMemento());  
  18.         System.out.println("恢复后的状态为:" + origi.getValue());  
  19.     }  
  20. }  
  1. package com.xtfggef.dp.state;  
  2.   
  3. /** 
  4.  * 状态类的核心类 
  5.  * 2012-12-1 
  6.  * @author erqing 
  7.  * 
  8.  */  
  9. public class State {  
  10.       
  11.     private String value;  
  12.       
  13.     public String getValue() {  
  14.         return value;  
  15.     }  
  16.   
  17.     public void setValue(String value) {  
  18.         this.value = value;  
  19.     }  
  20.   
  21.     public void method1(){  
  22.         System.out.println("execute the first opt!");  
  23.     }  
  24.       
  25.     public void method2(){  
  26.         System.out.println("execute the second opt!");  
  27.     }  
  28. }  
  1. package com.xtfggef.dp.state;  
  2.   
  3. /** 
  4.  * 状态模式的切换类   2012-12-1 
  5.  * @author erqing 
  6.  *  
  7.  */  
  8. public class Context {  
  9.   
  10.     private State state;  
  11.   
  12.     public Context(State state) {  
  13.         this.state = state;  
  14.     }  
  15.   
  16.     public State getState() {  
  17.         return state;  
  18.     }  
  19.   
  20.     public void setState(State state) {  
  21.         this.state = state;  
  22.     }  
  23.   
  24.     public void method() {  
  25.         if (state.getValue().equals("state1")) {  
  26.             state.method1();  
  27.         } else if (state.getValue().equals("state2")) {  
  28.             state.method2();  
  29.         }  
  30.     }  
  31. }  
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.           
  5.         State state = new State();  
  6.         Context context = new Context(state);  
  7.           
  8.         //设置第一种状态  
  9.         state.setValue("state1");  
  10.         context.method();  
  11.           
  12.         //设置第二种状态  
  13.         state.setValue("state2");  
  14.         context.method();  
  15.     }  
  16. }  
  1. public interface Visitor {  
  2.     public void visit(Subject sub);  
  3. }  
  1. public class MyVisitor implements Visitor {  
  2.   
  3.     @Override  
  4.     public void visit(Subject sub) {  
  5.         System.out.println("visit the subject:"+sub.getSubject());  
  6.     }  
  7. }  
  1. public interface Subject {  
  2.     public void accept(Visitor visitor);  
  3.     public String getSubject();  
  4. }  
  1. public class MySubject implements Subject {  
  2.   
  3.     @Override  
  4.     public void accept(Visitor visitor) {  
  5.         visitor.visit(this);  
  6.     }  
  7.   
  8.     @Override  
  9.     public String getSubject() {  
  10.         return "love";  
  11.     }  
  12. }  
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.           
  5.         Visitor visitor = new MyVisitor();  
  6.         Subject sub = new MySubject();  
  7.         sub.accept(visitor);      
  8.     }  
  9. }  
  1. public interface Mediator {  
  2.     public void createMediator();  
  3.     public void workAll();  
  4. }  
  1. public class MyMediator implements Mediator {  
  2.   
  3.     private User user1;  
  4.     private User user2;  
  5.       
  6.     public User getUser1() {  
  7.         return user1;  
  8.     }  
  9.   
  10.     public User getUser2() {  
  11.         return user2;  
  12.     }  
  13.   
  14.     @Override  
  15.     public void createMediator() {  
  16.         user1 = new User1(this);  
  17.         user2 = new User2(this);  
  18.     }  
  19.   
  20.     @Override  
  21.     public void workAll() {  
  22.         user1.work();  
  23.         user2.work();  
  24.     }  
  25. }  
  1. public abstract class User {  
  2.       
  3.     private Mediator mediator;  
  4.       
  5.     public Mediator getMediator(){  
  6.         return mediator;  
  7.     }  
  8.       
  9.     public User(Mediator mediator) {  
  10.         this.mediator = mediator;  
  11.     }  
  12.   
  13.     public abstract void work();  
  14. }  
  1. public class User1 extends User {  
  2.   
  3.     public User1(Mediator mediator){  
  4.         super(mediator);  
  5.     }  
  6.       
  7.     @Override  
  8.     public void work() {  
  9.         System.out.println("user1 exe!");  
  10.     }  
  11. }  
  1. public class User2 extends User {  
  2.   
  3.     public User2(Mediator mediator){  
  4.         super(mediator);  
  5.     }  
  6.       
  7.     @Override  
  8.     public void work() {  
  9.         System.out.println("user2 exe!");  
  10.     }  
  11. }  
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Mediator mediator = new MyMediator();  
  5.         mediator.createMediator();  
  6.         mediator.workAll();  
  7.     }  
  8. }  
  1. public interface Expression {  
  2.     public int interpret(Context context);  
  3. }  
  1. public class Plus implements Expression {  
  2.   
  3.     @Override  
  4.     public int interpret(Context context) {  
  5.         return context.getNum1()+context.getNum2();  
  6.     }  
  7. }  
  1. public class Minus implements Expression {  
  2.   
  3.     @Override  
  4.     public int interpret(Context context) {  
  5.         return context.getNum1()-context.getNum2();  
  6.     }  
  7. }  
  1. public class Context {  
  2.       
  3.     private int num1;  
  4.     private int num2;  
  5.       
  6.     public Context(int num1, int num2) {  
  7.         this.num1 = num1;  
  8.         this.num2 = num2;  
  9.     }  
  10.       
  11.     public int getNum1() {  
  12.         return num1;  
  13.     }  
  14.     public void setNum1(int num1) {  
  15.         this.num1 = num1;  
  16.     }  
  17.     public int getNum2() {  
  18.         return num2;  
  19.     }  
  20.     public void setNum2(int num2) {  
  21.         this.num2 = num2;  
  22.     }  
  23.       
  24.       
  25. }  
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.   
  5.         // 计算9+2-8的值  
  6.         int result = new Minus().interpret((new Context(new Plus()  
  7.                 .interpret(new Context(9, 2)), 8)));  
  8.         System.out.println(result);  
  9.     }  
  10. }  

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:Java开发中的23种设计模式(转)

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。