设计模式_抽象工厂模式(Abstract Factory)

package com.abstract_factory;

/**
 * 动物接口,抽象发声方法
 * @author 83998
 *
 */
public interface Animal {
	void sound();
}

package com.abstract_factory;

/**
 * 动物工厂接口
 * @author 83998
 *
 */
public interface AnimalFactory {
	/**
	 *创造动物方法,返回一个动物
	 * @return
	 */
	Animal creat();
}

package com.abstract_factory;

/**
 * 猫类,动物接口的实现类之一
 * @author 83998
 *
 */
public class Cat implements Animal {

	private String type;
	private String color;
	private int sex;

	public Cat(String type, String color, int sex) {
		super();
		this.type = type;
		this.color = color;
		this.sex = sex;
	}

	@Override
	public void sound() {
		System.out.println("mewo mewo mewo!");
	}

}

package com.abstract_factory;

/**
 * 猫工厂,动物工厂接口的实现类之一
 * @author 83998
 *
 */
public class CatFactory implements AnimalFactory {

	@Override
	public Animal creat() {
		return new Cat("布偶", "white", 1);
	}

}

package com.abstract_factory;

/**
 * 狗类,动物接口的实现类之一
 * @author 83998
 *
 */
public class Dog implements Animal {

	private String type;
	private String color;
	private int sex;

	public Dog(String type, String color, int sex) {
		super();
		this.type = type;
		this.color = color;
		this.sex = sex;
	}

	@Override
	public void sound() {
		System.out.println("wang wang wang!");
	}

}

package com.abstract_factory;

/**
 * 狗工厂类,动物工厂接口的实现类之一
 * @author 83998
 *
 */
public class DogFactory implements AnimalFactory {

	@Override
	public Animal creat() {
		return new Dog("哈士奇", "black", 1);
	}

}

package com.abstract_factory;

/**
 * 女孩类
 * @author 83998
 *
 */
public class Girl {
	/**
	 * 与动物玩
	 * @param animal
	 */
	public void playWith(Animal animal) {
		animal.sound();
	}
}

package com.abstract_factory;

/**
 * 测试类
 * @author 83998
 *
 */
public class Test {
	public static void main(String[] args) throws ClassNotFoundException {
		new Girl().playWith(new CatFactory().creat());
		new Girl().playWith(new DogFactory().creat());
	}
}

发布了340 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Chill_Lyn/article/details/103643759
今日推荐