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();
        }

    控制台打印信息如下:

    待更新。。。

  • 相关阅读:
    html5_css 3 学习指南__转
    MySQL常见故障处理手册_转
    MYSQL出错代码列表——转
    Redhat 6环境下安装Oracle 12c的方法
    Wireshark入门:分析DHCP协议的运行
    重命名Oracle数据库的表空间(Renaming a Tablespace)
    Oracle DB 分区特性概述 Overview of Partitions
    Oracle Database Concepts:介绍模式对象(Introduction to Schema Objects)
    Supporting Connected Routes to Subnet Zero
    Secondary IP Addressing
  • 原文地址:https://www.cnblogs.com/ckfeng/p/13111262.html
Copyright © 2011-2022 走看看