LandAnimal.java

public interface LandAnimal {
public void run();
}

WaterAnimal .java

public interface WaterAnimal {
public void swim();
}

Cat .java

public class Cat implements LandAnimal {
@Override
public void run() {
Log.i("msg","cat is runing");
}
}

Dog .java

public class Dog implements LandAnimal {
@Override
public void run() {
Log.i("msg","dog is runing");
}
}

Fish .java

public class Fish implements WaterAnimal {
@Override
public void swim() {
Log.i("msg","Fish is swiming");
}
}

Shark .java

public class Shark implements WaterAnimal {
@Override
public void swim() {
Log.i("msg","Shark is swiming");
}
}

AbstractFactory .java

public abstract class AbstractFactory {
public abstract LandAnimal getDog();
public abstract LandAnimal getCat();
public abstract WaterAnimal getFish();
public abstract WaterAnimal getShark();
}

AnimalFactory.java

public class AnimalFactory extends AbstractFactory {
@Override
public LandAnimal getDog() {
return new Dog();
}

@Override
public LandAnimal getCat() {
return new Cat();
}

@Override
public WaterAnimal getFish() {
return new Fish();
}

@Override
public WaterAnimal getShark() {
return new Shark();
}

}

使用方法如下:

AnimalFactory factory = new AnimalFactory();
LandAnimal cat = factory.getCat();
LandAnimal dog = factory.getDog();
WaterAnimal fish = factory.getFish();
WaterAnimal shark = factory.getShark();
cat.run();
dog.run();
fish.swim();
shark.swim();