工厂模式

工厂模式

属于创建型模式

专门定义一个类来负责创建一个接口的一系列实现类的实例;即负责创建一些列有公共父类或者实现接口的对象

为什么使用工厂模式

  1. 使用工厂模式, 将创建实例和使用实例进行分离, 更便于后期的维护和扩展;实现了解耦
  2. 工厂模式可以减少重复代码, 创建实例的代码只要重复调用工厂模式中的创建方法就行了

简单工厂模式

简单工厂模式又叫静态工厂方法模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//父类
public abstract class Animal {

private String kindName;

public String getKindName() {
return kindName;
}

public void setKindName(String kindName) {
this.kindName = kindName;
}

public void breathe(){
System.out.println("呼吸中...");
}

public abstract void eat();

}

//子类dog
public class Dog extends Animal {

@Override
public void eat() {
System.out.println("狗啃骨头...");
}
}

//子类cat
public class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃鱼...");
}
}

//工厂类
public class AnimalFactory {

public static Animal getAnimal(String name){
if (name=="dog"||name=="Dog"){
Animal dog=new Dog();
dog.setKindName("dog");
return dog;
}else if (name=="cat"||name=="Cat") {
Animal cat = new Cat();
cat.setKindName("dog");
return cat;
}else{
System.out.println("出错");
return null;
}
}
}

抽象工厂模式

当简单工厂模式要创建的对象非常多, 或者工厂类有它自己的实现类了,代码量也会增多, 不易维护.
上述代码的例子下, AnimalFactory有了继承它的DogFactory, CatFactory创建的对象变成ChinaDog
ChinaCat EnglishDog EnglishCat..怎么办呢

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 使用者
public class Zoo {
AbstractAnimalFactory abstractAnimalFactory=null;
public void setAnimal(String country,String kind){
if (kind=="dog"){
abstractAnimalFactory=new DogFactoryAbstract();
}else if (kind=="cat"){
abstractAnimalFactory=new CatFactoryAbstract();
}else{
System.out.println("工厂错误");
}
abstractAnimalFactory.createAnimal(country);
}
}

// 抽象工厂
public abstract class AbstractAnimalFactory {
public abstract Animal createAnimal(String name);
}

// 子类实现工厂
public class CatFactoryAbstract extends AbstractAnimalFactory {

@Override
public Animal createAnimal(String country) {
if (country == "chinese") {
return new ChineseCat();
} else if (country == "english") {
return new EnglishCat();
} else {
System.out.println("错误");
return null;
}
}
}

public class DogFactoryAbstract extends AbstractAnimalFactory {

@Override
public Animal createAnimal(String country) {
if (country == "chinese") {
return new ChineseDog();
} else if (country == "english") {
return new EnglishDog();
} else {
System.out.println("错误");
return null;
}
}
}