zoukankan      html  css  js  c++  java
  • 设计模式GOF23之工厂模式01

    简单工厂模式和工厂方法模式

    工厂模式核心:分工

    简单工厂模式不符合OCP(Open-Closed Princinple)原则,扩展时需要更改原代码

    工厂方法模式增加了类复杂度代码复杂度等,所以一般使用简单工厂模式

    普通代码

    public interface Car {
      void run();
    }

    public class Audi implements Car{
     @Override
     public void run() {
       System.out.println("奥迪在奔跑!!!");
     }
    }
    public class Bmw implements Car {
     @Override
     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 interface Car {
      void run();
    }

    public class Audi implements Car{
     @Override
     public void run() {
       System.out.println("奥迪在奔跑!!!");
     }
    }
    public class Bmw implements Car {
     @Override
     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;
       }
      }
    }
    public class Demo02 {
      public static void main(String[] args) {
       Car c1=CarFactory.getCar("宝马");
       Car c2=CarFactory.getCar("奥迪");
       
       c1.run();
       c2.run();
    }
    工厂方法模式
    public interface Car {
      void run();
    }
    public class Bmw implements Car {
     @Override
     public void run() {
       System.out.println("BMW在奔跑!!!");
     }
    }
    public class Audi implements Car{
     @Override
     public void run() {
       System.out.println("奥迪在奔跑!!!");
     }
    }
    public interface CarFactory {
      Car getCar();
    }
    public class AudiFactory implements CarFactory{
     @Override
     public Car getCar() {
      return new Audi();
     }
    }
    public class BmwFactory implements CarFactory{
     @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();
      }
    }
  • 相关阅读:
    阅读笔记:管理学
    Vs2010中文版MSDN 安装方法
    .NET 产品版权保护方案 (.NET源码加密保护)
    WPF 判断是否为设计(Design)状态
    重写成员时违反了继承安全性规则。重写方法的安全可访问性必须与所重写方法的安全可访问性匹配。
    没有为此解决方案配置选中要生成的项目 .
    何崚谈阿里巴巴前端性能优化最佳实践
    Oracle10GODP连接11G数据库,出现ORA 1017用户名/口令无效; 登录被拒绝 的问题
    HTTP、TCP、UDP、Socket (转)
    编译的时候生成.g.cs还有.g.i.cs,有什么区别?
  • 原文地址:https://www.cnblogs.com/code-fun/p/11311534.html
Copyright © 2011-2022 走看看