java GOF23 design patterns - simple factory pattern Adv

It does not modify the existing code, but add the code
does not deal with all classes, only the interface and implementation class total of dealing with
public class Cilent {

public static void main(String[] args) {

    Car c1=new AudiFactory().createCar();
    Car c2=new ByadiFactory().createCar();
    Car c3=new BenzFactory().createCar();

    c1.run();
    c2.run();
    c3.run();
}

}

Interface:
public interface Car {

void run();
}
实现1:
public class Benz implements Car {

public void run()
{
    System.out.println("Benz");
}

}
实现2:
public class Byadi implements Car{

public void run()
{
    System.out.println("Byadi");
}

}
Achieve 3:

public class Audi implements Car {

public void run()
{
    System.out.println("Audi");
}

}
Plant:
Interface:

public interface CarFactory {

Car createCar();

}
Achieve 1:

public class AudiFactory implements CarFactory{

public Car createCar()
{
    return new Audi();
}

}
To achieve 2:

public class BenzFactory implements CarFactory {

public Car createCar()
{
    return new Benz();
}
}

Achieve 3:

public class ByadiFactory implements CarFactory {

public Car createCar()
{
    return new Byadi();
}
}

Guess you like

Origin blog.51cto.com/14437184/2440448