1 package com.shejimoshi.structural.Flyweight; 2 3 4 /** 5 * 功能:运用共享技术有效地支持大量细粒度的对象,这个就是作为享元的类 6 * 适用:1、一个应用程序使用了大量的对象 7 * 2、完全由于使用大量的对象、造成很大的存储开销 8 * 3、对象的大多数状态都可以改变为外部状态 9 * 4、如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象 10 * 5、应用程序不依赖于对象标识 11 * 时间:2016年2月27日下午10:12:01 12 * 作者:cutter_point 13 */ 14 public abstract class Phone 15 { 16 public abstract void use(); 17 }
1 package com.shejimoshi.structural.Flyweight; 2 3 4 /** 5 * 功能:苹果手机享元 6 * 时间:2016年2月27日下午10:23:27 7 * 作者:cutter_point 8 */ 9 public class ApplePhone extends Phone 10 { 11 private String type; 12 13 public ApplePhone(String type) 14 { 15 this.type = type; 16 } 17 18 @Override 19 public void use() 20 { 21 System.out.println("使用"+ type +"苹果手机"); 22 } 23 24 }
1 package com.shejimoshi.structural.Flyweight; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 7 /** 8 * 功能:这个就是享元工厂 9 * 时间:2016年2月27日下午10:26:20 10 * 作者:cutter_point 11 */ 12 public class PhoneFactory 13 { 14 private static Map<String, Phone> phones = new HashMap<String, Phone>(); 15 16 public static Phone getPhone(String type) 17 { 18 //这里返回的值可以是新创建的,也可以是已经存在的 19 Phone phone = phones.get(type); 20 //如果不存在就新建 21 if(phone == null) 22 { 23 phone = new ApplePhone(type); 24 phones.put(type, phone); //添加进去 25 } 26 27 return phone; 28 } 29 30 public int size() 31 { 32 return phones.size(); 33 } 34 35 }
1 package com.shejimoshi.structural.Flyweight; 2 3 4 /** 5 * 功能:享元测试 6 * 时间:2016年2月27日下午10:34:46 7 * 作者:cutter_point 8 */ 9 public class Test 10 { 11 private PhoneFactory pf = new PhoneFactory(); 12 private Phone p1; 13 private Phone p2; 14 private Phone p3; 15 private Phone p4; 16 private Phone p5; 17 18 public Test() 19 { 20 p1 = pf.getPhone("银色"); 21 p2 = pf.getPhone("土豪金"); 22 p3 = pf.getPhone("土豪金"); 23 p4 = pf.getPhone("玫瑰金"); 24 p5 = pf.getPhone("银色"); 25 } 26 27 public void usethem() 28 { 29 p1.use(); 30 p2.use(); 31 p3.use(); 32 p4.use(); 33 p5.use(); 34 System.out.print("工厂大小:" + pf.size()); 35 } 36 37 public static void main(String[] args) 38 { 39 Test t = new Test(); 40 t.usethem(); 41 } 42 }
结果:
使用银色苹果手机 使用土豪金苹果手机 使用土豪金苹果手机 使用玫瑰金苹果手机 使用银色苹果手机 工厂大小:3