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 = ToyFactory(); Toy toy = tf.getToy('Dog'); toy.talk(); -->> Wow toy = tf.getToy('Cat'); toy.talk(); -->> Meow
Note
系统设计基础题,用class Dog
和class Cat
继承interface Toy
,然后在ToyFactory
里按照String type
生成需要的类就可以了。
Solution
interface Toy { void talk(); } class Dog implements Toy { public void talk() { System.out.println("Wow"); } } class Cat implements Toy { public void talk() { System.out.println("Meow"); } } public class ToyFactory { public Toy getToy(String type) { Toy T = null; if (type.equals("Dog")) T = new Dog(); else if (type.equals("Cat")) T = new Cat(); return T; } }原文链接:https://www.f2er.com/javaschema/283973.html