zoukankan      html  css  js  c++  java
  • java开发中使用的工厂设计模式

    package gongchangdemo;
    /*
     * 在java开发中使用较多的一种设计模式:工厂模式:就是一个过渡端
     * 通过过度端来取得接口的实例化对象,这个过渡端就称为工厂factory
     * 这个模式主要是为了解决修改子类,必须要修改main方法,而main方法主要是客户端,客户端
     * 经常变来变去不太好,就引进:工厂模式
     */
    public class gongchangdemo {
    public static void main(String args[]) {
        //getinstance 方法是静态的所以可以用类名直接调用
        //fruit f =null ;
        //f = factory.getinstance("apple");
        //f.eat();
        //上面写得apple是固定的,能否通过初始化参数的方法,则可以选择任意的子类去标记
        fruit f = null;
        f = factory.getinstance(args[0]);
        if (f!=null) {
            f.eat();
        }
        
    }
    }
    //写一个接口
    interface fruit{
        //写一个吃的抽象类
        public abstract void eat();
    }
    //写一个子类去实现fruit
    class apple implements fruit{
        public void eat(){
            System.out.println("我在吃苹果");
        }
    }
    //再写一个子类去实现fruit
    class orange implements fruit{
        public void eat(){
            System.out.println("我在吃橘子");
        }
    }
    //写一个过渡端 类factory,获取接口的实例化对象
    class factory{
        //返回 fruit类型的,所以用fruit修饰
        public static fruit getinstance(String classname){
            //先初始化
            fruit f =null;
            //传过来的参数与子类名对比
            if ("apple".equals(classname)) {
                f = new apple();
            }
            if ("orange".equals(classname)) {
                f = new orange();
            }
            return f;
        }
        
    }
  • 相关阅读:
    利用python 学习数据分析 (学习四)
    numpy 模块常用方法
    利用python 学习数据分析 (学习三)
    numpy 常用方法2
    瞎JB逆
    Codeforces 907 矩阵编号不相邻构造 团操作状压DFS
    AT Regular 086
    矩阵快速幂 求斐波那契第N项
    指数循环节(指数降幂)
    Educational Codeforces Round 32
  • 原文地址:https://www.cnblogs.com/yuanyuan2017/p/6562009.html
Copyright © 2011-2022 走看看