1.简单工厂模式
public class FactorySimple {
public static Vehicle produce(String type) {
Vehicle vehicle = null;
if (type.equals("car")) {
vehicle = new Car();
return vehicle;
}
if (type.equals("bus")){
vehicle = new Bus();
return vehicle;
}
if (type.equals("bicycle")){
vehicle = new Bicycle();
return vehicle;
}
return vehicle;
}
}
public interface Vehicle {
void run();
}
public class Car implements Vehicle{
@Override
public void run() {
System.out.println("car run...");
}
}
public class Bus implements Vehicle{
@Override
public void run() {
System.out.println("bus run...");
}
}
public class Bicycle implements Vehicle {
@Override
public void run() {
System.out.println("bicycle run...");
}
}
public static void main(String[] args) {
SpringApplication.run(FactoryPatternDemoApplication.class, args);
Vehicle vehicle = FactorySimple.produce("bicycle");
vehicle.run();
}
2.常规工厂模式
public interface Animal {
public void run();
}
public class Cat implements Animal{
@Override
public void run() {
System.out.println("Cat run...");
}
}
public class CatFactory implements FactoryNormal{
@Override
public Animal produce() {
return new Cat();
}
}
public class Dog implements Animal {
@Override
public void run() {
System.out.println("Dog run...");
}
}
public class DogFactory implements FactoryNormal{
@Override
public Animal produce() {
return new Dog();
}
}
public interface FactoryNormal {
Animal produce();
}
public static void main(String[] args) {
FactoryNormal fn = new DogFactory();
Animal animal = fn.produce();
animal.run();
}
网友评论