zoukankan      html  css  js  c++  java
  • 设计模式 之 简单工厂模式

    简介

    写一个工厂类来进行对象的构建, 不用关心构造的细节, 细节交给工厂类来实现. 也称为静态工厂模式. 简单工厂模式

    缺点

    做不到不修改代码实现新的对象生成. 比如下面代码实现别的汽车, 你得修改工厂类.

    java

    public class ConsumerSecond {
        public static void main(String[] args) {
            Car car = CarFactory.getCar("五菱");
            Car car1 = CarFactory.getCar("特斯拉");
            car.name();
            car1.name();
        }
    }
    
    public class WuLing implements Car{
        @Override
        public void name() {
            System.out.println("五菱宏光");
        }
    }
    
    public class Tesla implements Car {
        public void name() {
            System.out.println("特斯拉");
        }
    }
    
    
    public interface Car {
        void name();
    }
    
    
    public class CarFactory {
        public static Car getCar(String car) {
            if(car.equals("五菱")){
                return new WuLing();
            }else if(car.equals("特斯拉")){
                return new Tesla();
            }else{
                return null;
            }
        }
    }
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    Linux
    python 鸢尾花数据集报表展示
    python 词云
    毕业设计回顾
    editor.md
    杂记
    垃圾回收器
    杂记
    随笔
    杂记
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14817375.html
Copyright © 2011-2022 走看看