美文网首页
设计模式之享元模式

设计模式之享元模式

作者: smallstrong | 来源:发表于2017-04-24 12:16 被阅读15次

    享元模式,刚好现在共享单车火,拿来开刀

    享元模式UML.png
    interface ShareBike{
        void ride();
    }
    

    抽象共享单车

    class ShareBikeOFO implements ShareBike{
        public void ride(){
            //小黄车驾到
        }
    }
    

    天朝小黄车

    class ShareBikeMoBai implements ShareBike{
        public void ride(){
            //摩拜单车
        }
    }
    

    50斤的摩拜单车

    class BikeType{
        public static final String OFO = "OFO";
        public static final String MOBAI = "MOBAI";
    }
    

    共享单车类型

    class ShareBikeFactory{
        HashMap shareBikeMaps = new HashMap();
        
        public ShareBikeFactory(){
            shareBikeFactory.put("BikeType.OFO",new ShareBikeOFO());
            shareBikeFactory.put("BikeType.MOBAI",new ShareBikeMoBai());
        }
        
        public ShareBike getShareBike(String type){
            if(BikeType.OFO.equals(type)){
                return (ShareBikeOFO)shareBikeMaps.get(type);
            }else if(BikeType.MOBAI.equals(type){
                return (ShareBikeMOBAI)shareBikeMaps.get(type);
            }
            return null;
        }
    }
    

    单车托管所

    public class Client{
        public static void main(String args[]){
            ShareBikeFactory mshareBikeFactory = new ShareBikeFactory();
            ShareBike shareBikeOFO,shareBikeMobai;
            shareBikeOFO  = mshareBikeFactory.get(BikeType.OFO);
            shareBikeMoBai  = mshareBikeFactory.get(BikeType.MOBAI);
            shareBikeOFO.ride();
            shareBikeMoBai.ride();
        }
    }
    

    客户端根据需求拿单车来骑车

    个人总结

    享元模式是为了避免大量创建对象省内存时候用的,Android中消息机制中Message用链表来存储消息实现消息复用就是用到这种模式。

    相关文章

      网友评论

          本文标题:设计模式之享元模式

          本文链接:https://www.haomeiwen.com/subject/dltpzttx.html