一.小结
工厂模式用于创建具有相同属性的产品的一种方式。根据产品是具体产品还是具体工厂可分为简单工厂模式和工厂方法模式,根据工厂的抽象程度可分为工厂方法模式和抽象工厂模式。
二.简单工厂模式
简单工厂模式通用UML图如下:
下面以一个书籍的分类来说明:
// 1.书籍基类
public interface IBook {
String content();
}
// 2.小说与传记两个具体的书籍类别
public class Novel implements IBook {
@Override
public String content() {
return "小说";
}
}
public class Biography implements IBook {
@Override
public String content() {
return "传记";
}
}
// 3.产生具体书籍的工厂
public final class BookFactory {
private BookFactory() {
}
public static IBook getBook(Class<? extends IBook> bookCls) {
IBook book = null;
try {
book = bookCls.getDeclaredConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return book;
}
}
// 4.情景类
public class Client {
public static void main(String[] args) {
IBook book = BookFactory.getBook(Novel.class);
System.out.println("Book: " + book.content());
}
}
三.工厂方法模式
// 1.书籍基类
// 2.小说与传记两个具体的书籍类别
// 3.工厂
public interface AbstractBookFactory {
IBook getBook();
}
public class NovelFactory implements AbstractBookFactory {
@Override
public IBook getBook() {
return new Novel();
}
}
public class BiographyFactory implements AbstractBookFactory {
@Override
public IBook getBook() {
return new Biography();
}
}
// 4.工厂帮助类
public final class FactoryBuilder {
private FactoryBuilder() {
}
public static Novel getNovel() {
return (Novel) new NovelFactory().getBook();
}
public static Biography getBiography() {
return (Biography) new BiographyFactory().getBook();
}
}
// 5.情景类
public class Client {
public static void main(String[] args) {
System.out.println(FactoryBuilder.getBiography().content());
}
}
四.抽象工厂
// 1.书籍基类
// 2.小说与传记两个具体的书籍类别
// 3.增加一个书迷基类、小说迷与传记迷两个具体的书迷类别
public interface IFan {
String like();
}
public class NovelFan implements IFan{
@Override
public String like() {
return "小说书迷";
}
}
public class BiographyFan implements IFan{
@Override
public String like() {
return "传记书迷";
}
}
// 4.修改工厂基类:增加一个书迷产品线;修改具体的工厂类
public interface AbstractFactory {
IBook getBook();
IFan getFan();
}
public class NovelFactory implements AbstractFactory {
@Override
public IBook getBook() {
return new Novel();
}
@Override
public IFan getFan() {
return new NovelFan();
}
}
public class BiographyFactory implements AbstractFactory {
@Override
public IBook getBook() {
return new Biography();
}
@Override
public IFan getFan() {
return new BiographyFan();
}
}
// 5.情景类
public class Client {
public static void main(String[] args) {
BiographyFactory biographyFactory = FactoryBuilder.getBiographyFactory();
System.out.println(biographyFactory.getBook().content() + " " + biographyFactory.getFan().like());
}
}