zoukankan      html  css  js  c++  java
  • 享元模式

    一、定义

    享元模式(Flyweight),运用共享技术有效的支持大量细粒度的对象。

    二、示例代码

    /*外部对象*/
    public class User {
        private String name;
    
        public User(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    }
    
    public abstract class WebSite {
        public abstract void use(User user);
    }
    
    public class ConcreteWebsite extends WebSite{
     private String name;
    
        public ConcreteWebsite(String name) {
            this.name = name;
        }
    
    
        @Override
        public void use(User user) {
            System.out.println("网站名:"+name+",用户名:"+user.getName());
        }
    }
    
    import java.util.HashMap;
    
    public class WebsiteFactory {
        private HashMap<String, WebSite> hashMap = new HashMap();
    
        public WebSite getWebSite(String name) {
            if (hashMap.containsKey(name)) {
                return hashMap.get(name);
            } else {
                ConcreteWebsite concreteWebsite = new ConcreteWebsite(name);
                hashMap.put(name, concreteWebsite);
                return new ConcreteWebsite(name);
            }
        }
        public int countWeb(){
            return hashMap.size();
        }
    }
    
    public class Client {
        public static void main(String[] args) {
            WebsiteFactory websiteFactory=new WebsiteFactory();
           WebSite webSite  =websiteFactory.getWebSite("首页");
           User user=new User("huni");
           webSite.use(user);
           WebSite webSite2  =websiteFactory.getWebSite("标题");
           User user2=new User("knock");
           webSite2.use(user2);
           WebSite webSite3  =websiteFactory.getWebSite("标题");
           User user3=new User("jack");
           webSite3.use(user3);
            System.out.println("生成的网站对象数量:"+   websiteFactory.countWeb());
    
    
        }
    }
    
    
  • 相关阅读:
    DecimalPercentageConverter
    Asp.Net 性能 ViewState 压缩的2种方法
    Listbox template
    Datagrid template for listbox and textbox
    ToPercentConverter : IValueConverter
    繁體中文
    Silverlight ComboBox 设置选中项
    鲁迅:纪念刘和珍君
    ASP.NET系统整合DiscuzNT3.6之注意事项
    [转]js动态创建json类型
  • 原文地址:https://www.cnblogs.com/yfy-/p/12254390.html
Copyright © 2011-2022 走看看