java设计模式笔记

来源:互联网 发布:苹果移动数据怎么开 编辑:程序博客网 时间:2024/05/17 08:35

1.Singleton

作用:保证java应用程序中,一个class 只有一个实例存在。

实现:1.定义一个类,构造函数为private ,所有方法为static 其他类对它的引用全部是通过类名直接引用。

      private SingleClass() {}      public static String getMethod1() {}public static ArrayList getMethod2() {}

            2.定义一个类,构造函数为private,有一个static的private的该类变量,通过一个public的getInstance方法获得对他的引用,继而调用其中的方法。

      private staitc SingleClass _instance = null;      private SingleClass() {}      public static SingleClass getInstance() {          if (_instance == null) {_instance = new SingleClass();}          return _instance; }      public String getMethod1() {}      public ArrayList getMethod2() {}


2.Prototype

作用:用于创建对象,尤其是当创建对象需要许多时间和资源的时候,在java中prototype的实现是通过方法clone(),该方法定义在java的根对象Object中,因此,java中的其他对象只要覆盖它就行。通过clone()可以从一个对象获得更多的对象。

      public class Prototype implements Cloneable {        private String Name;        public rototype(String Name) {this.Name = Name; }        public void setName(String Name) {this.Name = Name; }        public String getName() {return Name; }        public Object clone() {            try{return super.clone();            }catch(CloneNotSupportedException cnse){                cnse.printStackTrace();                return null;            }        }}      Prototype p = new Prototype("My First Name");      Prototype p1 = p.clone();      p.setName("My Second Name");      Prototype p2 = p.clone();




原创粉丝点击