简单工厂模式和工厂方法模式
工厂模式核心:分工
简单工厂模式不符合OCP(Open-Closed Princinple)原则,扩展时需要更改原代码
工厂方法模式增加了类复杂度代码复杂度等,所以一般使用简单工厂模式
普通代码
public interface Car {
void run();
}
public class Audi implements Car{
@Override
public void run() {
System.out.println("奥迪在奔跑!!!");
}
public void run() {
System.out.println("奥迪在奔跑!!!");
}
}
public class Bmw implements Car {
@Override
public void run() {
System.out.println("BMW在奔跑!!!");
}
public void run() {
System.out.println("BMW在奔跑!!!");
}
}
public class Demo01 {
public static void main(String[] args) {
Car c1=new Audi();
Car c2=new Bmw();
c1.run();
c2.run();
public static void main(String[] args) {
Car c1=new Audi();
Car c2=new Bmw();
c1.run();
c2.run();
}
简单工厂模式
public interface Car {
void run();
}
public class Audi implements Car{
@Override
public void run() {
System.out.println("奥迪在奔跑!!!");
}
public void run() {
System.out.println("奥迪在奔跑!!!");
}
}
public class Bmw implements Car {
@Override
public void run() {
System.out.println("BMW在奔跑!!!");
}
public void run() {
System.out.println("BMW在奔跑!!!");
}
}
/**
* 简单工厂模式
* 破坏了OCP原则修改时需要改代码
* @author 小帆敲代码
*
*/
public class CarFactory {
public static Car getCar(String type) {
if(type.equals("奥迪")) {
return new Audi();
}else if(type.equals("宝马")) {
return new Bmw();
}else {
return null;
}
}
}
* 简单工厂模式
* 破坏了OCP原则修改时需要改代码
* @author 小帆敲代码
*
*/
public class CarFactory {
public static Car getCar(String type) {
if(type.equals("奥迪")) {
return new Audi();
}else if(type.equals("宝马")) {
return new Bmw();
}else {
return null;
}
}
}
public class Demo02 {
public static void main(String[] args) {
Car c1=CarFactory.getCar("宝马");
Car c2=CarFactory.getCar("奥迪");
c1.run();
c2.run();
public static void main(String[] args) {
Car c1=CarFactory.getCar("宝马");
Car c2=CarFactory.getCar("奥迪");
c1.run();
c2.run();
}
工厂方法模式
public interface Car {
void run();
}
void run();
}
public class Bmw implements Car {
@Override
public void run() {
System.out.println("BMW在奔跑!!!");
}
public void run() {
System.out.println("BMW在奔跑!!!");
}
}
public class Audi implements Car{
@Override
public void run() {
System.out.println("奥迪在奔跑!!!");
}
public void run() {
System.out.println("奥迪在奔跑!!!");
}
}
public interface CarFactory {
Car getCar();
}
Car getCar();
}
public class AudiFactory implements CarFactory{
@Override
public Car getCar() {
return new Audi();
}
}
public Car getCar() {
return new Audi();
}
}
public class BmwFactory implements CarFactory{
@Override
public Car getCar() {
return new Bmw();
}
}
@Override
public Car getCar() {
return new Bmw();
}
}
public class Client {
public static void main(String[] args) {
Car c1=new AudiFactory().getCar();
Car c2=new BmwFactory().getCar();
c1.run();
c2.run();
}
public static void main(String[] args) {
Car c1=new AudiFactory().getCar();
Car c2=new BmwFactory().getCar();
c1.run();
c2.run();
}
}