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

    和String达到一样的目的,节省空间

    package com.test.pattern.flyweight;
    
    import java.util.Hashtable;
    
    abstract class Flyweight {
        public abstract void operation();
    }
    
    class ConcreteFlyweight extends Flyweight {
        
        private String str;
        public ConcreteFlyweight(String str) {
            this.str=str;
        }
        @Override
        public void operation() {
            System.out.println("Concrete---Flyweight: "+str);
        }
    }
    
    //再定义一个工厂方法类
    class FlyweightFactory {
        private Hashtable flyweights = new Hashtable();
        public Flyweight getFlyweight(Object obj) {
            Flyweight flyweight = (Flyweight)flyweights.get(obj);
            if(flyweight == null) {
                flyweight = new ConcreteFlyweight((String) obj);
                flyweights.put(obj, flyweight);
            }
            return flyweight;
        }
        public int getFlyweightSize() {
            return flyweights.size();
        }
    }
    public class FlyweightTest {
        FlyweightFactory factory = new FlyweightFactory();
        Flyweight fly1,fly2,fly3,fly4,fly5;
        public static void main(String[] args) {
            System.out.println("The Flyweight Pattern");
            FlyweightTest test = new FlyweightTest();
            test.showFlyweight();
        }
        public FlyweightTest() {
            fly1 = factory.getFlyweight("Google");
            fly2 = factory.getFlyweight("Qutr");
            fly3 = factory.getFlyweight("Google");
            fly4 = factory.getFlyweight("Google");
            fly5 = factory.getFlyweight("Google");
        }
        public void showFlyweight() {
            fly1.operation();
            fly2.operation();
            fly3.operation();
            fly4.operation();
            fly5.operation();
            int objSize = factory.getFlyweightSize();
            System.out.println("objSize = " + objSize);
        }
    }
  • 相关阅读:
    Python 第四十九章 css 补充
    Python 第四十八章 css样式
    Python 第四十七章 css介绍
    iOS 流媒体 基本使用 和方法注意
    iOS 展示 gif
    iOS UIImage UIImageView 展示图片 不变形 处理
    UIImageView 获取图片的 宽 高
    iOS tabbar 上面更换任意图
    iOS 屏幕原点坐标 && 导航栏风格的自定义
    iOS NSDateFormatter 不安全线程 处理
  • 原文地址:https://www.cnblogs.com/heben/p/5784557.html
Copyright © 2011-2022 走看看