zoukankan      html  css  js  c++  java
  • java 设计模式之单利模式以及代理模式(静态)

    1:单利模式:

    public class Singleton {

        private static Singleton uniqueInstance = null;

     

        private Singleton() {

           // Exists only to defeat instantiation.

        }

     

        public static Singleton getInstance() {

           if (uniqueInstance == null) {

               uniqueInstance = new Singleton();

           }

           return uniqueInstance;

        }

        // Other methods...

    }

     

     

    代理模式(静态):

     package com;  
          
          
        /** 
         * 车站接口-【抽象角色】 
         *  
         * @author abing 
         *  
         */  
        interface Station {  
            void sellTicks();// 卖票  
            void transport();// 运输乘客  
        }  
          
        /** 
         * 火车站实现类-【具体角色】 
         *  
         * @author abing 
         *  
         */  
        class TrainStationImpl implements Station {  
          
            @Override  
            public void sellTicks() {  
                System.out.println("TrainStation  sell tickets");  
          
            }  
          
            @Override  
            public void transport() {  
                System.out.println("TrainStation  transport passenger");  
                  
            }  
        }  
          
        /** 
         * 该类做为火车站的一个代理直接供客户端调用-【代理角色】 
         *  
         * @author abing 
         *  
         */  
        class StationProxy implements Station {  
            Station sta = new TrainStationImpl();  
          
            @Override  
            public void sellTicks() {  
                sta.sellTicks();//代理类中调用真实角色的方法。  
            }  
            public void otherOperate() {  
                System.out.println("do some other things...");  
            }  
            @Override  
            public void transport() {  
                System.out.println("StationProxy can not transport");  
            }  
        }  
          
        /** 
         * 客户端测试类 
         *  
         * @author abing 
         *  
         */  
        public class StaticProxyDemo {  
            public static void main(String[] args) {  
                Station station = new StationProxy();//客户端直接操作代理类,避免了客户端与真实类的直接交涉  
                station.sellTicks();  
            }  
          
        } 

     

     

  • 相关阅读:
    js中的数据类型和判断数据类型
    MVC,MVVM,MVP等设计模式的分析
    mvc框架详解
    插件推荐系列
    响应式区间
    js短路原理:&&, ||
    不错的表单样式
    测试ip
    Python模拟登陆万能法
    iphone 端 ipunt输入框光标偏移
  • 原文地址:https://www.cnblogs.com/yujian-bcq/p/3443744.html
Copyright © 2011-2022 走看看