UML
用户类 用于网站的客户账号 是网站类的外部状态
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
网站抽象类
public abstract class WebSite {
public abstract void use(User user);
}
具体的网站
public class ConcreteWebSite extends WebSite {
private String websiteName;
public ConcreteWebSite(String websiteName) {
this.websiteName = websiteName;
}
@Override
public void use(User user) {
System.out.println("网站名->" + websiteName + " 用户名->" + user.getName());
}
}
网站工厂
import java.util.Hashtable;
public class WebSiteFactory {
private Hashtable<String, WebSite> hashtable = new Hashtable<>();
public WebSite getWebSite(String key) {
if (hashtable.containsKey(key)) {
return hashtable.get(key);
} else {
WebSite concreteWebSite = new ConcreteWebSite(key);
hashtable.put(key, concreteWebSite);
return concreteWebSite;
}
}
public int getCount() {
return hashtable.size();
}
}
测试类
public class Main {
public static void main(String[] args) {
WebSiteFactory factory = new WebSiteFactory();
WebSite f1 = factory.getWebSite("产品展示");
f1.use(new User("小菜"));
WebSite f2 = factory.getWebSite("产品展示");
f2.use(new User("大鸟"));
WebSite f3 = factory.getWebSite("产品展示");
f3.use(new User("笨蛋"));
WebSite f31 = factory.getWebSite("博客");
f31.use(new User("钢蛋"));
WebSite f32 = factory.getWebSite("博客");
f32.use(new User("鸡蛋"));
WebSite f33 = factory.getWebSite("博客");
f33.use(new User("大神"));
System.out.println("网站总数--->" + factory.getCount());
}
}
运行结果