Parent
import java.util.ArrayList;
import java.util.List;
public abstract class Website {
protected List<Page> pages = new ArrayList<>();
public List<Page> getPages() {
return pages;
}
public Website() {
this.createWebsite();
}
// Crux of the factory pattern
public abstract void createWebsite();
}
Children
public class Blog extends Website {
@Override
public void createWebsite() {
pages.add(new PostPage());
pages.add(new AboutPage());
pages.add(new CommentPage());
pages.add(new ContactPage());
}
}
public class Shop extends Website {
@Override
public void createWebsite() {
pages.add(new CartPage());
pages.add(new ItemPage());
pages.add(new SearchPage());
}
}
Factory
public class WebsiteFactory {
public static Website getWebsite(WebsiteType siteType) {
switch(siteType) {
case BLOG : {
return new Blog();
}
case SHOP : {
return new Shop();
}
default : {
return null;
}
}
}
}
网友评论