单子设计模式

来源:互联网 发布:淘宝如何开话费店 编辑:程序博客网 时间:2024/04/25 17:55

 1   什么是设计模式:  在大量实践中总结和理论化之后,优选的代码结构,编程风格,以及解决问题的方案。

2设计模式的四个组成部分:

                一 模式名称:(pattern name): 描述模式所解决的问题方案以及效果。

               二问题(Problem): 描述何时使用模式

              三解决问题的方案(Solution): 描述模式的组成部份和各部份相互职责和协作关系。

              四效果(consequnce):描述使用模式的效果以及使用模式对应的权衡问题。

3单设计模式

      需求背景 :采用一定的办法在整个软件中,某个类的实例对象在内存中只存在一个,也就是说这个类的实例对象只允许产生一个,外部不能根据该类的构造方法任意产生对象。

解决方式:构造方法定义为私有的,不允许外部对其直接访问。

                    定义一个公共的静态方法取得本类产生实例对象的方法。

                    定义一个静态的本类类型的成员变量保存私有方法产生的实例对象。

 

package cn.edu.csu.staticoper;

public class SingletonPattern {
  private static SingletonPattern sp = null;
  private SingletonPattern(){
  }
  public static SingletonPattern getInstance(){
    if(sp == null){
      sp = new SingletonPattern();
    }
    return sp;
  }
}
package cn.edu.csu.staticoper;

public class Test {

  /**
   * @param args
   */
  public static void main(String[] args) {
    SingletonPattern sp1 = SingletonPattern.getInstance();
    SingletonPattern sp2 = SingletonPattern.getInstance();
    System.out.println(sp1);
    System.out.println(sp2);
    if(sp1 == sp2){
      System.out.println("the same object");
    }
  }
}