简单工厂
工厂模式属于创建型模式:用于描述“怎样创建对象”,一般分为工厂模式和抽象工厂。
引入简单工厂模式,这种模式不属于工厂模式,但是为了便于理解后续的两种模式,便引入了这个概念,同时还有一个重要的思想----再暴露逻辑的前提下生成一个实例。
设想以下有如下这样的一个场景,当你想造一间房子的时候,你肯定需要门,但是自己一个一个造就太慢了,所以你打算去工厂购买木门,让工厂去造,而你只需要说出你需要的门的要求就好。
在产品的规范的定义上我们很简单的就想到了接口,接口其很重要的一个功能就是为了定义规范,在简单了解需求后我们就可以得出大概的思路。
interface Door{ //通过接口来规范产品
public float getWidth();
public float getHeight();
}
class WoodenDoor implements Door{ //木门
protected float width;
protected float height;
public WoodenDoor(float width,float height) {
this.width = width;
this.height = height;
}
@Override
public float getWidth() {
System.out.println("获取木门的宽度");
return width;
}
@Override
public float getHeight() {
System.out.println("获取木门的高度");
return height;
}
}
class IronWoodenDoor implements Door{ //铁门
protected float width;
protected float height;
public IronWoodenDoor(float width,float height) {
this.width = width;
this.height = height;
}
@Override
public float getWidth() {
System.out.println("获取铁门的宽度");
return width;
}
@Override
public float getHeight() {
System.out.println("获取铁门的高度");
return height;
}
}
class DoorFactory{
public static Door makerDoor(float width,float height,String type) //造门的工厂
{
if (type.equals("wood")) //根据条件判断是顾客需要什么门
{
return new WoodenDoor(width,height);
}
else if (type.equals("iron"))
{
return new IronWoodenDoor(width,height);
}
else {
return null;
}
}
}
//可以看出在对用户需求的门上用了if-else来判断,这段代码所书写的不是那么好
//那么接下来就引入的工厂模式和抽象工厂。
主方法如下:
public static void main(String[] args) {
DoorFactory doorfactory = new DoorFactory();
Door wood1 = DoorFactory.makerDoor(20,100,"wood");
System.out.println(wood1.getWidth());
System.out.println(wood1.getHeight());
}