首页 > 其他 > 详细

lintcode:形状工厂

时间:2016-07-07 17:11:08      阅读:174      评论:0      收藏:0      [点我收藏+]

题目

工厂模式是一种常见的设计模式。实现一个形状工厂 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;
    }
}

 



lintcode:形状工厂

原文:http://www.cnblogs.com/theskulls/p/5650691.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!