设计模式实战:内容管理系统的设计与实现

时间:2025-01-17 12:12:00
// 内容抽象类 abstract class Content { protected String title; protected String body; public String getTitle() { return title; } public String getBody() { return body; } @Override public String toString() { return "Title: " + title + "\nBody: " + body; } } // 文章内容类 class Article extends Content { private String author; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } } // 页面内容类 class Page extends Content { private String layout; public String getLayout() { return layout; } public void setLayout(String layout) { this.layout = layout; } } // 媒体内容类 class Media extends Content { private String mediaType; public String getMediaType() { return mediaType; } public void setMediaType(String mediaType) { this.mediaType = mediaType; } } // 内容建造者接口 interface ContentBuilder { void buildTitle(String title); void buildBody(String body); Content getContent(); } // 文章建造者 class ArticleBuilder implements ContentBuilder { private Article article = new Article(); @Override public void buildTitle(String title) { article.title = title; } @Override public void buildBody(String body) { article.body = body; } public void buildAuthor(String author) { article.setAuthor(author); } @Override public Content getContent() { return article; } } // 页面建造者 class PageBuilder implements ContentBuilder { private Page page = new Page(); @Override public void buildTitle(String title) { page.title = title; } @Override public void buildBody(String body) { page.body = body; } public void buildLayout(String layout) { page.setLayout(layout); } @Override public Content getContent() { return page; } } // 媒体建造者 class MediaBuilder implements ContentBuilder { private Media media = new Media(); @Override public void buildTitle(String title) { media.title = title; } @Override public void buildBody(String body) { media.body = body; } public void buildMediaType(String mediaType) { media.setMediaType(mediaType); } @Override public Content getContent() { return media; } }