博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
设计模式 之 享元模式
阅读量:5071 次
发布时间:2019-06-12

本文共 1705 字,大约阅读时间需要 5 分钟。

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

 

转载于:https://www.cnblogs.com/heben/p/5784557.html

你可能感兴趣的文章
[置顶] Android仿人人客户端(v5.7.1)——人人授权访问界面
查看>>
ES6内置方法find 和 filter的区别在哪
查看>>
Android实现 ScrollView + ListView无滚动条滚动
查看>>
java学习笔记之String类
查看>>
UVA 11082 Matrix Decompressing 矩阵解压(最大流,经典)
查看>>
硬件笔记之Thinkpad T470P更换2K屏幕
查看>>
iOS开发——缩放图片
查看>>
HTTP之URL的快捷方式
查看>>
满世界都是图论
查看>>
配置链路聚合中极小错误——失之毫厘谬以千里
查看>>
蓝桥杯-分小组-java
查看>>
Android Toast
查看>>
iOS开发UI篇—Quartz2D使用(绘制基本图形)
查看>>
docker固定IP地址重启不变
查看>>
桌面图标修复||桌面图标不正常
查看>>
JavaScript基础(四)关于对象及JSON
查看>>
JAVA面试常见问题之Redis篇
查看>>
jdk1.8 api 下载
查看>>
getElement的几中属性介绍
查看>>
HTML列表,表格与媒体元素
查看>>