模式可以分为三大类:创建型模式(Creational Patterns)、结构型模式(Structural Patterns)、行为型模式(Behavioral Patterns)。还有另一类设计模式:J2EE 设计模式。
1,工厂模式
动物接口
public interface Animal {
void eat();
}
猫类
public class Cat implements Animal {
@Override
public void eat() {
System.out.println("cat eat");
}
}
狗类
public class Dog implements Animal{
@Override
public void eat() {
System.out.println("dog eat");
}
}
鱼类
public class Fish implements Animal {
@Override
public void eat() {
System.out.println("fish eat");
}
}
动物工厂
public class AnimalFactory {
public static Object getAnimal(Class<? extends Animal> clazz){
Object obj=null;
try {
obj=Class.forName(clazz.getName()).newInstance();
}catch (Exception e){
e.printStackTrace();
}
return obj;
}
}
public class Test {
public static void main(String[] args){
Animal animal=(Animal) AnimalFactory.getAnimal(Fish.class);
animal.eat();
}
}
2,抽象工厂模式
抽象工厂类
public abstract class AbstractFactory {
abstract Object getAnimal(Class<? extends Animal> clazz);
abstract Object getColor(Class<? extends Color> clazz);
}
动物接口
public interface Animal {
void eat();
}
颜色接口
public interface Color {
void draw();
}
抽象工厂
public class FactoryProduct {
public static Object getClass(Class<? extends AbstractFactory> clazz){
Object obj=null;
try {
obj=Class.forName(clazz.getName()).newInstance();
}catch (Exception e){
e.printStackTrace();
}
return obj;
}
}
动物工厂
public class AnimalFactory extends AbstractFactory{
@Override
Object getAnimal(Class<? extends Animal> clazz){
Object obj=null;
try {
obj=Class.forName(clazz.getName()).newInstance();
}catch (Exception e){
e.printStackTrace();
}
return obj;
}
@Override
Color getColor(Class<? extends Color> clazz) {
return null;
}
}
颜色工厂
public class ColorFactory extends AbstractFactory{
@Override
Animal getAnimal(Class<? extends Animal> clazz) {
return null;
}
@Override
Object getColor(Class<? extends Color> clazz) {
Object obj=null;
try {
obj=Class.forName(clazz.getName()).newInstance();
}catch (Exception e){
e.printStackTrace();
}
return obj;
}
}
鱼类
public class Fish implements Animal {
@Override
public void eat() {
System.out.println("fish eat");
}
}
猫类
public class Cat implements Animal {
@Override
public void eat() {
System.out.println("cat eat");
}
}
红色类
public class Red implements Color {
@Override
public void draw() {
System.out.println("draw red");
}
}
黄色类
public class Yellow implements Color{
@Override
public void draw() {
System.out.println("draw yellow");
}
}
测试类
public class Test1 {
public static void main(String[] args){
AnimalFactory animalFactory=(AnimalFactory) FactoryProduct.getClass(AnimalFactory.class);
Animal animal=(Animal) animalFactory.getAnimal(Fish.class);
animal.eat();
ColorFactory colorFactory=(ColorFactory) FactoryProduct.getClass(ColorFactory.class);
Color color=(Color) colorFactory.getColor(Red.class);
color.draw();
}
}
打印结果