java设计模式创建篇------工厂模式

java设计模式创建篇------工厂模式

核心思想

定义一个接口用于完成相关对象的创建,并将各种对象的创建统一于这个接口,子类通过实现该接口可以决定具体创建哪一个类。

相关实现

产品

“工厂的产品”是最终要生成的目标类。
由于是工厂化生产,所以其产生的产品之间应当有相关的共性,我们通过一个接口将其抽象出来。
我们以服装厂为例子来看一下,每件衣服都有自己的款式。我们用show函数来表示。

public abstract class Clothes{
	public abstract void style ();
}

接下来就可以看看衣服了,为了表示方便,我们以衣服的颜色来表示款式。

public class BlueClothes extends Clothes{
	@Override
	public void style() {
		System.out.println("It is blue");
	}
}
public class GreenClothes extends Clothes{
	@Override
	public void style() {
		System.out.println("It is green");
	}
}
public class RedClothes extends Clothes{
	@Override
	public void style() {
		System.out.println("It is red");
	}
}

这样我们这个服装厂可以生产三种样式的衣服了,r,g,b都有了

简单工厂

工厂刚刚起步,我们没有那么多的订单,所以我们应对的需求比较简单。只需要根据颜色生产就好。

public class ClothesFactory {
	public Clothes getShape(String color) {
		if (color.equals("r")) {
			return new RedClothes();
		} else if (color.equals("g")) {
			return new GreenClothes();
		} else if (color.equals("b")) {
			return new BlueClothes();
		} else {
			return null;
		}
	}
}

也可以将这一方法写成静态的便于后续的操作,也就是静态工厂。

public class ClothesFactory {
	public static Clothes getShape(String color) {
		if (color.equals("r")) {
			return new RedClothes();
		} else if (color.equals("g")) {
			return new GreenClothes();
		} else if (color.equals("b")) {
			return new BlueClothes();
		} else {
			return null;
		}
	}
}

完整实现

鉴于工厂的发展,我们可能会在多地设立工厂,也有可能跨行业生产,所有我们需要对原来的简单工厂进行完善。

public abstract class AbstractFactory {
	public abstract T createProduct(Class<T> cls);
}

通过多个工厂特点的抽象统一,我们将其创建的过程集中于一个抽象类中,并通过继承产生形式多样的子类工厂。

public class ClothesFactory extends AbstractFactory {
	@Override
    public T createProduct(Class<T> cls) {
    	Clothes clothes=null;
        String classname=cls.getName();
        try {
        	clothes= (Clothes) Class.forName(classname).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("机器故障");
        }
        return (T) clothes;
    }
}

这样我们不仅可以通过修改工厂类中的工厂方法,还可以创建新的工厂类来实现对新加的类的创建。

实际生产

我们通过简单的运用来看看其具体的使用过程

public class Product{
    public static void main(String[]args) {
        ClothesFactory clothesFactory = new ClothesFactory();
        RedClothes redClothes=clothesFactory.createProduct(RedClothes.class);
        redClothes.style();
        BlueClothes blueClothes=clothesFactory.createProduct(BlueClothes.class);
        blueClothes.style();
        GreenClothes greenClothes=clothesFactory.createProduct(GreenClothes.class);
        greenClothes.style();
    }
}

特点

较高的封装性使得我们可以忽略每个类具体的初始化过程,只需要通过相应的类名或是对应的约束字符串就可以实现对相关类的初始化。除此之外,其还有很好的扩展性,比如我们增加一个或是多个新的类,只要在接口方法的实现中增加有关新类的初始化语句即可。极大的降低了各模块之间的耦合性。

猜你喜欢

转载自blog.csdn.net/sinat_36945592/article/details/86705196
今日推荐