zoukankan      html  css  js  c++  java
  • 设计模式

    下面来回顾一下设计模式

    设计模式是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。

    23中设计模式。

    一、工厂模式

    步骤:首先创建一个接口,然后再创建实现接口类,再创建一个工厂类,最后使用该工厂,通过传递类型信息来获取实体类的对象。

    1.首先创建一个接口

    /**
     * 创建一个接口
     */
    public interface Shape {
        void draw();
    }

    2.创建是三个实现类

    创建逛街类里面拥有逛街的方法

    public class Circle implements Shape {
    
        @Override
        public void draw() {
            System.out.println("逛街的方法");
        }
    }

    创建运动类里面拥有运动的方法

    public class Rectangle implements Shape {
    
        @Override
        public void draw() {
            System.out.println("运动的方法");
        }
    }

    创建撩妹类里面拥有撩妹的方法

    public class Square implements Shape {
    
        @Override
        public void draw() {
            System.out.println("撩妹的方法");
        }
    }

    3.创建一个工厂

     /**
         * 使用 getShape 方法获取形状类型的对象
         * @param shapeType
         * @return
         */
        public Shape getShape(String shapeType){
            if(shapeType == null){
                return null;
            }
    
            if(shapeType.equalsIgnoreCase("逛街")){
                return new Circle();
            } else if(shapeType.equalsIgnoreCase("运动")){
                return new Rectangle();
            } else if(shapeType.equalsIgnoreCase("撩妹")){
                return new Square();
            }
            return null;
        }

    4.使用该工厂  生成基于给定信息的实体类的对象。

    public class FactoryPatternDemo {
        public static void main(String[] args) {
            ShapeFactory shapeFactory = new ShapeFactory();
    
            //获取 Circle 的对象,并调用它的 draw 方法
            Shape shape1=shapeFactory.getShape("逛街");
    
            //调用 Circle 的 draw 方法
            shape1.draw();
    
            //获取 Rectangle 的对象,并调用它的 draw 方法
            Shape shape2 = shapeFactory.getShape("运动");
    
            //调用 Rectangle 的 draw 方法
            shape2.draw();
    
            //获取 Square 的对象,并调用它的 draw 方法
            Shape shape3 = shapeFactory.getShape("撩妹");
    
            //调用 Square 的 draw 方法
            shape3.draw();
        }

    控制台打印信息如下:

    待更新。。。

  • 相关阅读:
    iOS:UIResponser控件的介绍(响应者)
    iOS:触摸控件UITouch、事件类UIEvent
    iOS:触摸事件和手势识别的介绍
    iOS:菜单控制器和菜单项:UIMenuController和UIMenuItem
    iOS:对GCD中 同步、异步、并行、串行的见解
    iOS:转载:同步、异步、并行、串行的详解
    iOS:GCD技术——仅仅执行一次和执行多次 dispatch_once和dispatch_apply
    pes and ts stream, how to convert
    5分钟搞定内存字节对齐
    sed 使用
  • 原文地址:https://www.cnblogs.com/ckfeng/p/13111262.html
Copyright © 2011-2022 走看看