摘要:这道题考了,具体概念如下除此之外,还需要注意正则表达式的写法。
Problem
Factory is design pattern in common usage. Implement a ShapeFactory that can generate correct shape.
Example</>复制代码
ShapeFactory sf = new ShapeFactory();
Shape shape = sf.getShape("Square");
shape.draw();
----
| |
| |
----
shape = sf.getShape("Triangle");
shape.draw();
/
/
/____
shape = sf.getShape("Rectangle");
shape.draw();
----
| |
----
Note
这道题考了interface & implementation & override,具体概念如下:
Interface: A Java interface is a bit like a class, except that it can only contain method signatures and fields, which is saying that it cannot contain any implementation of the methods. You can use interface to achieve polymorphism.
Implementation: To declare a class that implements an interface, you have to include an implements clause in the class definition. Your class can implement more than one interface.
Overriding: If subclass provides the specific/close implementation of the method that has been provided by one of its parent class, it is known as method overriding.
除此之外,还需要注意正则表达式的写法。
Solution</>复制代码
interface Shape {
void draw();
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println(" ----");
System.out.println("| |");
System.out.println(" ----");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println(" ----");
System.out.println("| |");
System.out.println("| |");
System.out.println(" ----");
}
}
class Triangle implements Shape {
@Override
public void draw() {
System.out.println(" /");
System.out.println(" / ");
System.out.println("/____");
}
}
public class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType.equalsIgnoreCase("Rectangle")) return new Rectangle();
else if (shapeType.equalsIgnoreCase("Square")) return new Square();
else if (shapeType.equalsIgnoreCase("Triangle")) return new Triangle();
return null;
}
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/65803.html
摘要:系统设计基础题,用和继承,然后在里按照生成需要的类就可以了。 Problem Factory is a design pattern in common usage. Please implement a ToyFactory which can generate proper toy based on the given type. Example ToyFactory tf = ...
摘要:假设需要创建一个矩形,我们可以这样做需要一个圆形也简单实际上,我们通常是在界面上,一般是工具栏上,放置两个按钮,让用户选择哪个按钮,然后创建此形状。 作为创建型设计模式,带有工厂名字的设计模式共有三个,分别是 Simple Factory Factory Method Abstract Factory 其中的 Simple Factory并不是GoF一书中的模式,但是它是最基础最常...
摘要:原文链接译者个人翻译,水平有限,如有错误欢迎指出,谢谢设计模式工厂模式工厂模式是中最常用的设计模式之一。这种类型的设计模式属于创建型模式下,创建一个对象最好的方式之一。调用圆的方法获得矩形的一个对象并调用它的方法。 原文链接译者:smallclover个人翻译,水平有限,如有错误欢迎指出,谢谢! 设计模式-工厂模式 工厂模式是Java中最常用的设计模式之一。这种类型的设计模式属于创建型...
摘要:原文链接译者个人翻译,水平有限,如有错误欢迎指出,谢谢设计模式抽象工厂模式抽象工厂的核心是一个超级工厂,而这个工厂能创建其他的工厂。在抽象工厂模式中,一个接口负责创建抽象与一个工厂相关的对象,不需要显示的指定它们的类。 原文链接译者:smallclover个人翻译,水平有限,如有错误欢迎指出,谢谢! 设计模式-抽象工厂模式 抽象工厂的核心是一个超级工厂,而这个工厂能创建其他的工厂。所以...
阅读 5073·2021-11-25 09:43
阅读 1429·2021-11-24 09:38
阅读 2082·2021-09-30 09:54
阅读 2950·2021-09-23 11:21
阅读 2447·2021-09-10 10:51
阅读 2461·2021-09-03 10:45
阅读 1281·2019-08-30 15:52
阅读 1882·2019-08-30 14:13