在Java模式的工厂模式中分为:普通工厂模式、多个工厂模式、抽象工厂模式
1、普通工厂模式
在普通工厂模式中,其实是对实现同一接口的类进行实例的创建,在工厂中进行类的创建。
代码示例如下:
1、创建一个其它类都需要继承的接口,其中接口中定义一个方法。
public interface Animal {
public void create();
}
2、创建两个实现类,继承接口同时重写接口中的方法。两个实现类中对重写的方法输出不同的值。
public class Cat implements Animal {
@Override
public void create() {
System.out.println("this is cat");
}
}
public class Dog implements Animal {
@Override
public void create(){
System.out.println("this is dog");
}
}
3、创建一个工厂,工厂中创建一个方法,在方法中通过判断来决定创建哪一个实体类。
public class AnimalFactory {
public Animal create(String type){
if ("dog".equals(type)){
return new Dog();
}else if ("cat".equals(type)){
return new Cat();
}else {
System.out.println("请输入正确的动物");
return null;
}
}
}
4、创建一个工厂测试类
public class FactoryTest {
public static void main(String[] args) {
AnimalFactory animalFactory = new AnimalFactory();
Animal animal = animalFactory.create("dog");
animal.create();
}
}
通过工厂模式,我们不需要对我们要使用的类一个一个来创建了,我们可以通过工厂类,通过一定的算法来实现我们需要的实体类的创建。这样减轻了内存的负载,只创建需要的类,同时减少冗余。
2、多个工厂模式
多个工厂模式是对工厂方法的改进,在普通工厂模式中,如果传递的字符串出错,那么就无法正确的创建对象,而多个工厂模式是提供多个工厂方法,分别创建对象。
1、创建统一的接口
package 多个工厂模式;
public interface Animal {
public void create();
}
2、创建实现接口的类
package 多个工厂模式;
public class Cat implements Animal {
@Override
public void create() {
System.out.println("this is cat");
}
}
3、创建实现接口的类
package 多个工厂模式;
public class Dog implements Animal {
@Override
public void create(){
System.out.println("this is dog");
}
}
4、创建工厂类
package 多个工厂模式;
public class AnimalFactory {
public Animal createDog(){
return new Dog();
}
public Animal createCat(){
return new Cat();
}
}
5、创建工厂测试类
package 多个工厂模式;
public class FactoryTest {
public static void main(String[] args) {
AnimalFactory animalFactory = new AnimalFactory();
Animal animal = animalFactory.createCat();
animal.create();
}
}
在普通工厂模式中,如果传入的字符串有问题,那么就无法创建对象,因此在多个工厂模式中,通过在工厂类中创建不同的方法来创建对象,因此在测试类中只要调用相对应的工厂中的方法就可以实现对象的创建。
3、抽象工厂模式
抽象工厂模式:
1、创建统一的接口
package 抽象工厂模式;
public interface Animal {
public void create();
}
2、创建实现接口的类
package 抽象工厂模式;
public class Cat implements Animal {
@Override
public void create() {
System.out.println("this is cat");
}
}
3、创建实现接口的类
package 抽象工厂模式;
public class Dog implements Animal {
@Override
public void create(){
System.out.println("this is dog");
}
}
4、创建一个工厂接口
package 抽象工厂模式;
public interface Action {
public Animal action();
}
5、创建工厂类实现工厂接口
package 抽象工厂模式;
public class CatFactory implements Action {
@Override
public Animal action() {
return new Cat();
}
}
6、创建工厂类实现工厂接口
package 抽象工厂模式;
public class DogFactory implements Action {
@Override
public Animal action() {
return new Dog();
}
}
7、创建工厂测试类
package 抽象工厂模式;
public class Test {
public static void main(String[] args) {
Action action = new CatFactory();
Animal animal = action.action();
animal.create();
}
}
如果你现在想增加一个功能:测试大熊猫,则只需做一个实现类,实现Animal接口,同时做一个工厂类,实现Action接口,就OK了,无需去改动现成的代码。这样做,拓展性较好!