zoukankan      html  css  js  c++  java
  • lintcode:形状工厂

    题目

    工厂模式是一种常见的设计模式。实现一个形状工厂 ShapeFactory 来创建不同的形状类。这里我们假设只有三角形,正方形和矩形三种形状。

    样例
    ShapeFactory sf = new ShapeFactory();
    Shape shape = sf.getShape("Square");
    shape.draw();
    >>  ----
    >> |    |
    >> |    |
    >>  ----
    
    shape = sf.getShape("Triangle");
    shape.draw();
    >>   /
    >>  /  
    >> /____
    
    shape = sf.getShape("Rectangle");
    shape.draw();
    >>  ----
    >> |    |
    >>  ----
    解题
    直接draw方法
    /**
     * Your object will be instantiated and called as such:
     * ShapeFactory sf = new ShapeFactory();
     * Shape shape = sf.getShape(shapeType);
     * shape.draw();
     */
    interface Shape {
        void draw();
    }
    
    class Rectangle implements Shape {
        // Write your code here
        public void draw(){
            System.out.println(" ----");
            System.out.println("|    |");
            System.out.println(" ----");    
        }
    }
    
    class Square implements Shape {
        // Write your code here
        public void draw(){
            System.out.println(" ----");
            System.out.println("|    |");
            System.out.println("|    |");
            System.out.println(" ----");    
        }
        
    }
    
    class Triangle implements Shape {
        // Write your code here
        public   void draw(){
            System.out.println("  /\");
            System.out.println(" /  \");
            System.out.println("/____\");  
        }
    }
    
    public class ShapeFactory {
        /**
         * @param shapeType a string
         * @return Get object of type Shape
         */
        public Shape getShape(String shapeType) {
            // Write your code here
            if(shapeType.equals("Square")){
                return new Square();
            }
            if(shapeType.equals("Rectangle")){
                return new Rectangle();
            }
            if(shapeType.equals("Triangle")){
                return new Triangle();
            }
            return null;
        }
    }


  • 相关阅读:
    android获取sd卡路径方法
    Log4Net的使用
    asp.net网站发布
    用网站(WebSite而不是WebProject)项目构建ASP.NET MVC网站
    Asp.Net MVC 路由
    面试题:两个栈模拟队列&&两个队列模拟栈
    TextBlob Quick Start
    链表基本操作题
    leetcode341 扁平化嵌套数组
    细说浏览器输入URL后发生了什么
  • 原文地址:https://www.cnblogs.com/theskulls/p/5650691.html
Copyright © 2011-2022 走看看