• 设计模式开始1--不明觉厉


    最近的一段时间在复习设计模式~分享给大家

    设计模式是思考然后实现的过程,所谓思考就是定义各种各样的接口,抽象类,所谓实现,就是各种实现接口或者继承抽象类的实现类。

    抛开接口和抽象类resovled的时候区别,接口体现的是顺序的思考顺序,抽象类体现的是顺序+共享的思考方式,举例来说明的话,汽车的生产需要组装,喷漆等过程 没有共享的过程所以需要接口进行实现,而对于三中电脑,每一种电脑都有不同的硬盘,光盘,但是假设他们的主板是一致的,那么便采用抽象类进行实现,因为抽象类允许方法的实现,所以在抽象类中可以对主板这个共享的相同的方法进行实现,这样子类便不用实现了。

    案例需求:

    计算圆,长方形的面积,要求自适应可以通过输入半径或者长,宽,输出对应的面积

    1.Interface Shape

    public interface Shape {
        public double calculateArea();
        public boolean input();
    }
    View Code

    2.Rect implements Shape

    public class Rect implements Shape {
        private float width;
        private float height;
        @Override
        public double calculateArea() {
            return width * height;
        }
        @Override
        public boolean input() {
            System.out.println("请分别输入,长,宽");
            Scanner s = new Scanner(System.in);
            width = s.nextFloat();
            height = s.nextFloat();
            return true;
        }
    }
    View Code

    2.Circle implements Shape 

    public class Circle implements Shape {
        private float r;
        @Override
        public double calculateArea() {
            return Math.PI * (double)(r*r);
        }
        @Override
        public boolean input() {
            System.out.println("请输出半径");
            Scanner s = new Scanner(System.in);
            r = s.nextFloat();
            return true;
        }
    }
    View Code

    3.ShapeProc uses Shape

    public class ShapeProc {
        private Shape shape;
        public ShapeProc(Shape shape)
        {
            this.shape = shape;
        }
        public double process()
        {
            shape.input();
            return shape.calculateArea();
        }
    }
    View Code

    4.Test test the simple design pattern

    public class Test {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Shape circle = new Circle();
            ShapeProc sp = new ShapeProc(circle);
            System.out.println(sp.process());
            sp = new ShapeProc(new Rect());
            System.out.println(sp.process());
        }
    }
    View Code

     4.当然也可以通过使用java的反射机制改写Test的方法,使其扩展性更好一些

    public class Test {
        public static void main(String[] args) throws Exception {
            // TODO Auto-generated method stub
            Shape circle = (Shape)Class.forName(args[0]).getConstructor().newInstance();
            ShapeProc sp = new ShapeProc(circle);
            System.out.println(sp.process());
        }
    }
    View Code
  • 相关阅读:
    深入理解JVM 运行时数据区域
    深入理解JVM 垃圾收集
    深入理解JVM 垃圾收集算法
    深入理解JVM HotSpot 虚拟机对象
    公司格式
    出现 Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation 问题
    vuex 中关于 mapActions 的作用
    vuerouter 路由传递参数的三种写法
    Android WebView禁用系统键盘
    直播CDN介绍
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4367760.html
Copyright © 2020-2023  润新知