简单工厂模式
- 简单工厂方法(静态工厂方法)模式就是由一个工厂对象决定创建出哪一种产品的实例。
- 定义一个创建对象的类,由这个类来封装实例化对象的行为。
- 在软件开发中,我们大量用到某种,某类,某对象时会用到工厂方法模式。
类图
![简单工厂模式类图](https://i-blog.csdnimg.cn/blog_migrate/1842bb45bf2ea96c79715724563ffebb.png)
案例
package simpleFactory;
public interface Desk {
String getType();
}
public class PlasticDesk implements Desk {
private String type = "塑料桌";
@Override
public String getType() {
return type;
}
}
package simpleFactory;
public class WoodenDesk implements Desk{
private String type = "木质桌";
@Override
public String getType() {
return type;
}
}
package simpleFactory;
public class DeskFactory {
public static Desk createDesk(Type type) {
switch (type) {
case WOODEN:
return new WoodenDesk();
case PLASTIC:
return new PlasticDesk();
default:
return null;
}
}
}
package simpleFactory;
public class Main {
public static void main(String[] args) {
Desk desk = DeskFactory.createDesk(Type.PLASTIC);
System.out.println(desk.getType());
}
}
工厂模式
介绍
- 工厂方法带参数,用参数区分要创建的不同类对象
- 每类对象分配一个工厂方法
UML图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e2695d2fc08acf8ec135fb352334d204.png)
案例
抽象工厂方法模式
介绍
UML图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e77926fde0433000eeaf2d28fe27bd34.png)
案例
public interface IDesk {
String getType();
}
public class HuNanPlasticDesk implements IDesk {
private String type = "湖南塑料桌";
@Override
public String getType() {
return type;
}
}
public class HuNanWoodenDesk implements IDesk {
private String type = "湖南木质桌";
@Override
public String getType() {
return type;
}
}
public class HeNanWoodenDesk implements IDesk {
private String type = "河南木质桌";
@Override
public String getType() {
return type;
}
}
public class HeNanPlasticDesk implements IDesk {
private String type = "河南塑料桌";
@Override
public String getType() {
return type;
}
}
public interface IDeskFactory {
IDesk CreateDesk( Type type);
}
public class HuNanDeskFactory implements IDeskFactory{
@Override
public IDesk CreateDesk(Type type) {
switch (type) {
case WOODEN:
return new HeNanWoodenDesk();
case PLASTIC:
return new HeNanPlasticDesk();
default:
return null;
}
}
}
public class HeNanDeskFactory implements IDeskFactory{
@Override
public IDesk CreateDesk(Type type) {
switch (type) {
case WOODEN:
return new HeNanWoodenDesk();
case PLASTIC:
return new HeNanPlasticDesk();
default:
return null;
}
}
}
public class Main {
public static void main(String[] args) {
HeNanDeskFactory heNanDeskFactory = new HeNanDeskFactory();
IDesk desk =heNanDeskFactory.CreateDesk(Type.PLASTIC);
System.out.println(desk.getType());
}
}