Flyweight_Pattern

package flyweight_pattern;

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;
    }
}

package flyweight_pattern;

public abstract class Website {
    public abstract void use(User user);
}

package flyweight_pattern;

public class ConcreteWebsite extends Website{
    private String name = "";
    public ConcreteWebsite(String name) {
        this.name = name;
    }
    @Override
    public void use(User user) {
        System.out.println("The type of website is " + name);
        System.out.println("The reader is " + user.getName());
    }
}

package flyweight_pattern;

import java.util.Hashtable;

public class WebsiteFactory {
    private Hashtable flyweights = new Hashtable();
    public Website getWebsiteCategory(String key) {
        if(!flyweights.containsKey(key)) {
            flyweights.put(key, new ConcreteWebsite(key));
        }
        return (Website)flyweights.get(key);
    }
    public int getWebsiteCount() {
        return flyweights.size();
    }
}

package flyweight_pattern;

public class Main {
    public static void main(String args[]) {
        WebsiteFactory f = new WebsiteFactory();
        User tom = new User("Tom");
        User sam = new User("Sam");
        
        Website fx = f.getWebsiteCategory("essay");
        fx.use(tom);
        Website fy = f.getWebsiteCategory("essay");
        fy.use(sam);
        Website fz = f.getWebsiteCategory("ppt");
        fz.use(tom);
        Website ft = f.getWebsiteCategory("presentation");
        ft.use(sam);
        Website fr = f.getWebsiteCategory("presentation");
        fr.use(tom);
        System.out.println(f.getWebsiteCount());
    }
}
This is a general introduction to the 23 design patterns:
https://blog.csdn.net/GZHarryAnonymous/article/details/81567214

See more source code:[GZHarryAnonymous](https://github.com/GZHarryAnonymous/Design_Pattern)

你可能感兴趣的:(Java)