码迷,mamicode.com
首页 > 其他好文 > 详细

num14---享元模式

时间:2020-02-18 09:26:30      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:http   图片   site   img   contain   ext   mamicode   hashmap   tor   

技术图片

 

 技术图片

 

 技术图片

 

 技术图片

 

 案例:

技术图片

 技术图片

 

 

 

public abstract class WebSite {

	public abstract void use(User user);//抽象方法
}

  

public class ConcreteWebSite extends WebSite {
	private String type = ""; //网站发布形式(类型)

	public ConcreteWebSite(String type) {
		this.type = type;
	}

	@Override
	public void use(User user) {
		System.out.println("网站发布形式:" + type + " 使用者:" + user.getName());
	}
}

  

public class User {
	
	private String name;
	
	public User(String name) {
		super();
		this.name = name;
	}
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

 

// 网站工厂类
public class WebSiteFactory {
	
	//集合,充当池的作用
	private HashMap<String, ConcreteWebSite> pool = new HashMap<>();
	
	//根据网站类型返回网站
	public WebSite getWebSiteCategory(String type) {
		if(!pool.containsKey(type)) {
			pool.put(type, new ConcreteWebSite(type));
		}
		return (WebSite)pool.get(type);
	}
	
	//获取池中数量
	public int getWebSiteCount() {
		return pool.size();
	}
}

  

public static void main(String[] args) {

		// 创建一个工厂类
		WebSiteFactory factory = new WebSiteFactory();

		WebSite webSite1 = factory.getWebSiteCategory("新闻");
		webSite1.use(new User("tom"));
		
		WebSite webSite2 = factory.getWebSiteCategory("博客");
		webSite2.use(new User("jack"));

		WebSite webSite3 = factory.getWebSiteCategory("博客");
		webSite3.use(new User("smith"));

		WebSite webSite4 = factory.getWebSiteCategory("博客");
		webSite4.use(new User("king"));
		
		System.out.println("容量=" + factory.getWebSiteCount());
	}

  

 

num14---享元模式

标签:http   图片   site   img   contain   ext   mamicode   hashmap   tor   

原文地址:https://www.cnblogs.com/dxxdsw/p/12324748.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!