美文网首页
Design Pattern - Simple Factory

Design Pattern - Simple Factory

作者: whicter | 来源:发表于2017-07-01 03:08 被阅读0次

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

相关文章

网友评论

      本文标题:Design Pattern - Simple Factory

      本文链接:https://www.haomeiwen.com/subject/bflwcxtx.html