栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

设计模式-享元模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

设计模式-享元模式

享元模式
  • 抽象享元
    • 食物
  • 具体享元
    • 面条
    • 饺子
    • 米饭
  • 享元工厂
    • 食堂
  • 测试


享元模式属于结构型模式

它尝试重用现有的对象,若没有现成的,则创建对象
主要为了减少创建对象的数量,以减少内存占用,
常用在需要缓冲的场景,例如Java的常量池。

包含抽象享元、具体享元类、享元工厂三个角色。

抽象享元 食物
package com.example.duohoob.dp.flyweight;


public interface Food {

	
	void taste(String extrinsicState);
	
}

具体享元 面条
package com.example.duohoob.dp.flyweight;


public class Noodle implements Food {

	
	private String intrinsicState = "面条";
	
	@Override
	public void taste(String extrinsicState) {
		// TODO Auto-generated method stub
		System.out.println(extrinsicState + "吃到了" + intrinsicState + "的味道");
	}

}
饺子
package com.example.duohoob.dp.flyweight;


public class Dumpling implements Food {

	
	private String intrinsicState = "饺子";
	
	@Override
	public void taste(String extrinsicState) {
		// TODO Auto-generated method stub
		System.out.println(extrinsicState + "吃到了" + intrinsicState + "的味道");
	}

}
米饭
package com.example.duohoob.dp.flyweight;


public class Rice implements Food {

	
	private String intrinsicState = "米饭";
	
	@Override
	public void taste(String extrinsicState) {
		// TODO Auto-generated method stub
		System.out.println(extrinsicState + "吃到了" + intrinsicState + "的味道");
	}

}
享元工厂 食堂
package com.example.duohoob.dp.flyweight;

import java.util.HashMap;
import java.util.Map;


public class Canteen {

	
	public Map meals = new HashMap();
	
	public Food getFood(String foodName) {
		// 如果没有就现做,相反有的话就不用
		if (!meals.containsKey(foodName)) {
			if ("面条".equals(foodName)) {
				meals.put(foodName, new Noodle());
			}
			if ("饺子".equals(foodName)) {
				meals.put(foodName, new Dumpling());
			}
			if ("米饭".equals(foodName)) {
				meals.put(foodName, new Rice());
			}
		}
		return meals.get(foodName);
	}
	
}
测试
package com.example.duohoob.dp.flyweight;


public class FlyweightTest {

	public static void main(String[] args) {
		Canteen canteen = new Canteen();
		// a要吃面条
		Food noodle1 = canteen.getFood("面条");
		noodle1.taste("a");
		// b要吃面条
		Food noodle2 = canteen.getFood("面条");
		noodle2.taste("b");
		// c要吃饺子
		Food dumpling = canteen.getFood("饺子");
		dumpling.taste("c");
		// d要吃米饭
		Food rice = canteen.getFood("米饭");
		rice.taste("d");
		
		System.out.println();
		System.out.println("abcd共吃了四份饭菜");
		System.out.println("但食堂却只需要准备" + canteen.meals.keySet().size() + "种饭菜");
	}
	
}

运行

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1013970.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号