一、定义
享元模式就是运用共享技术有效的支持大量细粒度的对象。
二、框架运用
String中的享元模式
三、实战
1、实现类
public abstract class WebSite {
protected String name;
public WebSite(String name) {
this.name = name;
}
public abstract void show(User user);
}
public class ConcreteWebSite extends WebSite {
public ConcreteWebSite(String name) {
super(name);
}
@Override
public void show(User user) {
System.out.println("网站名称:"+name+"|网站账号:"+user.getAccount()+"|网站密码:"+user.getPassword());
}
2、实体类
@Data
public class User {
private String account;
private String password;
public User(String account, String password) {
this.account = account;
this.password = password;
}
}
3、工厂类
public class WebSiteFactory {
private Map<String,WebSite> webSiteMap = new HashMap<>();
public WebSite getWebSite(String key){
if (!webSiteMap.containsKey(key)){
webSiteMap.put(key,new ConcreteWebSite(key));
}
return webSiteMap.get(key);
}
public int getWebSiteCount(){
return webSiteMap.size();
}
}
4、运行和结果
public class Client {
public static void main(String[] args) {
WebSiteFactory factory = new WebSiteFactory();
WebSite webSiteA = factory.getWebSite("A");
WebSite webSiteB = factory.getWebSite("B");
User userA = new User("范闲","123456");
User userB = new User("王启年","654321");
webSiteA.show(userA);
webSiteB.show(userB);
System.out.println(factory.getWebSiteCount());
}
}
Connected to the target VM, address: '127.0.0.1:56232', transport: 'socket'
网站名称:A|网站账号:范闲|网站密码:123456
网站名称:B|网站账号:王启年|网站密码:654321
2
Disconnected from the target VM, address: '127.0.0.1:56232', transport: 'socket'
来源:CSDN
作者:hy_coming
链接:https://blog.csdn.net/hy_coming/article/details/103654820