Object Oriented Design
  • Introduction
  • OOD Case Studies
    • Black Jack
    • Shape Factory
    • Toy Factory
    • Parking Lot
    • Friendship Service
    • Vending Machine
    • Coffee Maker
    • GFS Client
    • Singleton
  • Introduction
Powered by GitBook
On this page
  • Description
  • Example
  • Solution

Was this helpful?

  1. OOD Case Studies

Toy Factory

Description

Factory is a design pattern in common usage. Please implement a ToyFactory

which can generate proper toy based on the given type.

Example

Example 1:

Input:
ToyFactory tf = ToyFactory();
Toy toy = tf.getToy('Dog');
toy.talk(); 
Output:
Wow

Example 2:

Input:
ToyFactory tf = ToyFactory();
toy = tf.getToy('Cat');
toy.talk();
Output:
Meow

Solution

/**
* This reference program is provided by @jiuzhang.com
* Copyright is reserved. Please indicate the source for forwarding
*/

/**
 * Your object will be instantiated and called as such:
 * ToyFactory tf = new ToyFactory();
 * Toy toy = tf.getToy(type);
 * toy.talk();
 */
interface Toy {
    void talk();
}

class Dog implements Toy {
    // Write your code here
    @Override
    public void talk() {
        System.out.println("Wow");
   }
}

class Cat implements Toy {
    // Write your code here
    @Override
    public void talk() {
        System.out.println("Meow");
   }
}

public class ToyFactory {
    /**
     * @param type a string
     * @return Get object of the type
     */
    public Toy getToy(String type) {
        // Write your code here
        if (type == null) {
            return null;
        }        
        if (type.equalsIgnoreCase("Dog")) {
            return new Dog();
        } else if(type.equalsIgnoreCase("Cat")) {
            return new Cat();         
        }
        return null;
    }
}
PreviousShape FactoryNextParking Lot

Last updated 5 years ago

Was this helpful?