Java设计模式

1、单例设计模式:一个类只实例化一个对象。有饿汉式和懒汉式两种方式。

 1 package pack;
 2 public class Test1
 3 {
 4     public static void main(String[] args) 
 5     {
 6         System.out.println(Single.getInstance()==Single.getInstance());
 7     }
 8 }
 9 //单例设计模式的饿汉式的程序,一个类只允许生成一个对象
10 class Single
11 {
12     private static final Single s=new Single();
13     Single(){}
14     public static Single getInstance()
15     {
16         return s;
17     }
18     public String str;
19     public String fun(String str)
20     {
21         return str;
22     }
23 }
24 //单例设计模式的懒汉式的程序,一个类只允许生成一个对象,对象是延迟加载
25 //用同步的方式来解决懒汉式的多线程访问的安全问题,但会比较低效
26 class Single1
27 {
28     private static Single1 s=null;
29     Single1(){}
30     public static Single1 getInstance()
31     {
32         if(s==null)
33         {
34             //懒汉式的锁是类字节码
35             synchronized(Single1.class)
36             {
37                 if(s==null) 
38                     s=new Single1();
39             }
40         }
41         return s;
42     }
43 }

2、模版方法设计模式:定义功能时,功能的一部分是确定的,一部分是不确定的,而确定的部分在使用不确定的部分,那么这是就将不确定的部分暴露出去,由该类的子类去实现。

原文地址:https://www.cnblogs.com/joeshine/p/4385424.html