Java开发-3大设计模式
            
            
              设计模式
单例设计模式
- 构造方法私有化 
- 声明一个本类对象 
- 给外部提供一个静态方法获取对象实例 
饿汉式
- 类加载后创建对象,程序结束后回收该对象
- 占用内存时间长,效率高
|  | public class C0401SingleMode {private C0401SingleMode() {
 }
 private static C0401SingleMode s = new C0401SingleMode();
 public static C0401SingleMode getInstance(){
 return s;
 }
 }
 
 | 
懒汉式
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | public class C0401SingleMode {
 
 private C0401SingleMode() {
 }
 
 private static C0401SingleMode single;
 
 public static C0401SingleMode getInstance(){
 
 if (single == null){
 single = new C0401SingleMode();
 }
 return single;
 }
 }
 
 | 
- 工具类(只有功能方法,没有属性)
- 工具类频繁使用
- 节省资源避免重复创建对象
私有化构造+静态方法实现单例较消耗内存
简单工厂模式
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 
 | public class C0402FactorMode {public static void main(String[] args) {
 
 Product Phone = new Phone();
 Phone.work();
 
 Product Phone1 = ProductFactory.getProduct("Phone");
 Phone1.work();
 }
 }
 
 class ProductFactory{
 
 public static Product getProduct(String need){
 
 switch (need){
 case "Phone":return new Phone();
 case "Computer" : return new Computer();
 }
 return null;
 }
 }
 
 interface Product {
 void work();
 }
 
 class Phone implements Product{
 
 @Override
 public void work() {
 System.out.println("Phone working");
 }
 }
 
 class Computer implements Product{
 
 @Override
 public void work() {
 System.out.println("Computer working");
 }
 }
 
 | 
静态代理模式
- 定义接口
- 接口实现类重写接口方法
- 定义代理类实现接口
- 私有化接口对象属性
- 定义返回值为接口对象的显式构造器、并指定传参为接口类型的对象,指定传参对象作为构造器指定对象(即调用传参对象)
 
- new 接口对象,new代理模式对象并把接口对象作为传参
- 调用方法
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 
 | public class C0403ProxyMode {public static void main(String[] args) {
 Action userAction = new UserAction();
 
 ActionProxy target = new ActionProxy(userAction);
 target.doAction();
 }
 }
 class ActionProxy implements Action{
 
 private Action target;
 
 public ActionProxy(){}
 
 public ActionProxy(Action target) {
 
 this.target = target;
 }
 
 @Override
 public void doAction() {
 
 long stratTime = System.currentTimeMillis();
 
 this.target.doAction();
 Long endTime = System.currentTimeMillis();
 System.out.println("is used time:"+(endTime-stratTime));
 }
 }
 
 
 interface Action{
 void doAction();
 }
 
 class UserAction implements Action{
 @Override
 public void doAction() {
 System.out.println("working");
 }
 }
 
 |