/**
* Description:
* - Abstract post class.
* - Represents a generic post on a web site.
*
*/
public abstract class Post {
private Long id;
private String title;
private String content;
private LocalDateTime createdAt;
private LocalDateTime publishedAt;
...
}
/**
* Description:
* - Represents a news post.
*
*/
public class NewsPost extends Post {
private String headline;
private LocalDate newsTime;
...
}
/**
* Description:
* - Represents a blog post.
*
*/
public class BlogPost extends Post {
private String author;
private String[] tags;
...
}
/**
* Description:
* - Represents a product information post.
*
*/
public class ProductPost extends Post {
private String imageUrl;
private String name;
...
}
/**
* Description:
* - This class acts as a Simple Factory for creation of different posts
*
*/
public class PostFactory {
/**
* Description:
* - Instantiate subclass of Post
* - Give type as the criteria for which subclass to instantiate
*
*/
public static Post createPost(String type) {
switch(type) {
case "blog":
return new BlogPost();
case "news":
return new NewsPost();
case "product":
return new ProductPost();
default:
throw new IllegalArgumentException("Post type is unknown.");
}
}
}
public class Client {
public static void main(String[] args) {
Post post = PostFactory.createPost("blog");
System.out.println(post);
}
}
Simple Factory can be just a method in existing class. Adding a separate class however allows other parts of your code to use simple factory more easily.
Simple Factory itself doesn't need any state tracking so it's best to keep this as a static method.
Simple Factory will in turn may use other design pattern like Builder to construct objects.
In case you want to specialize your Simple Factory in sub classes, you need Factory method design pattern instead.
Simple Factory
Factory Method