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();  
            }  
          
        } 

     

     

  • 相关阅读:
    【转】Windows Socket网络编程(二)套接字编程原理
    获取本地IP地址,并在IP CONTROL控件中显示出来
    PAT 1021 Deepest Root[并查集、dfs][难]
    1025 PAT Ranking[排序][一般]
    PAT 1028 List Sorting[排序][一般]
    PAT 1023 Have Fun with Numbers[大数乘法][一般]
    PAT 1026 Table Tennis[比较难]
    Andrew NgML第十章应用机器学习的建议
    PAT 1020 Tree Traversals[二叉树遍历]
    PAT 1022 Digital Library[map使用]
  • 原文地址:https://www.cnblogs.com/yujian-bcq/p/3443744.html
Copyright © 2011-2022 走看看