1.工厂模式:创建型,主要用来生产对象。
- 简单工厂模式:简单粗暴。
- 工厂方法模式:和工具类一样,方便简单,耦合性高。
- 抽象工厂模式:低耦合。
2.示例
- 类型
package test.javase.demo.pattern;
public class Animal {
private String color;//颜色
private String sex;//公母
public Animal(String color, String sex) {
this.color = color;
this.sex = sex;
}
@Override
public String toString() {
return "Animal [color=" + color + ", sex=" + sex + "]";
}
}
package test.javase.demo.pattern;
public class Dog extends Animal {
private String voice;
public Dog(String color, String sex, String voice) {
super(color, sex);
this.voice = voice;
}
@Override
public String toString() {
return "Dog [voice=" + voice + "]";
}
}
package test.javase.demo.pattern;
public class Sheep extends Animal {
private String legs;//腿的数量
public Sheep(String color, String sex, String legs) {
super(color, sex);
this.legs = legs;
}
@Override
public String toString() {
return "Sheep [legs=" + legs + "]";
}
}
package test.javase.demo.pattern;
public class AnimalFactory {
public Animal create(String flag){
Animal animal = null;
if("dog".equals(flag)){
animal = new Dog("black","M","wangwang");
}
if("sheep".equals(flag)){
animal = new Sheep("white","F","4");
}
return animal;
}
}
2.工厂方法模式
package test.javase.demo.pattern;
public class FactoryMethod {
public static Animal creatDog(){
return new Dog("black","M","wangwang");
}
public static Animal creatSheep(){
return new Sheep("white","F","4");
}
}
3.抽象工厂模式
package test.javase.demo.pattern;
public interface AbstractFactory {
Animal getAnimal();
}
package test.javase.demo.pattern;
public class DogFactory implements AbstractFactory {
@Override
public Animal getAnimal() {
return new Dog("black","M","wangwang");
}
}
package test.javase.demo.pattern;
public class SheepFactory implements AbstractFactory {
@Override
public Animal getAnimal() {
return new Sheep("white","F","4");
}
}
4.测试main方法
package test.javase.demo;
import test.javase.demo.pattern.AbstractFactory;
import test.javase.demo.pattern.Animal;
import test.javase.demo.pattern.AnimalFactory;
import test.javase.demo.pattern.Dog;
import test.javase.demo.pattern.DogFactory;
import test.javase.demo.pattern.FactoryMethod;
import test.javase.demo.pattern.Sheep;
import test.javase.demo.pattern.SheepFactory;
public class MainTestClass {
public static void main(String args[]){
AnimalFactory fact = new AnimalFactory();
Animal animal1 = fact.create("dog");
Animal animal2 = fact.create("sheep");
System.out.println(animal1.toString());
System.out.println(animal2.toString());
Animal animal3 = FactoryMethod.createDog();
Animal animal4 = FactoryMethod.createSheep();
System.out.println(animal3.toString());
System.out.println(animal4.toString());
AbstractFactory dogFactory = new DogFactory();
Dog dog = (Dog)dogFactory.getAnimal();
AbstractFactory sheepFactory = new SheepFactory();
Sheep sheep = (Sheep)sheepFactory.getAnimal();
System.out.println(dog.toString());
System.out.println(sheep.toString());
}
}