Python - Write program to implement "Has-a" Relationships

Requirements

The product shop is a composite object: it has an oven, and it has employees like servers and chefs.

When a customer enters and places an order, the components of the shop spring into action-the server takes the order, the chef makes the product, and so on.

Hint

Composition reflects the relationships between parts, called "has-a" relationships.

Demo

from __future__ import print_function 

class Employee: # from  w  w  w .  j av  a  2 s .co m
    def __init__(self, name, salary=0): 
        self.name   = name 
        self.salary = salary 
    def giveRaise(self, percent): 
        self.salary = self.salary + (self.salary * percent) 
    def work(self): 
        print(self.name, "does stuff") 
    def __repr__(self): 
        return "<Employee: name=%s, salary=%s>" % (self.name, self.salary) 

class Chef(Employee): 
    def __init__(self, name): 
        Employee.__init__(self, name, 50000) 
    def work(self): 
        print(self.name, "makes food") 

class Server(Employee): 
    def __init__(self, name): 
        Employee.__init__(self, name, 40000) 
    def work(self): 
        print(self.name, "interfaces with customer") 

class ProductRobot(Chef): 
    def __init__(self, name): 
        Chef.__init__(self, name) 
    def work(self): 
        print(self.name, "makes product") 
        
class Customer: 
    def __init__(self, name): 
        self.name = name 
    def order(self, server): 
        print(self.name, "orders from", server) 
    def pay(self, server): 
        print(self.name, "pays for item to", server) 

class Oven: 
    def bake(self): 
        print("oven bakes") 

class ProductShop: 
    def __init__(self): 
        self.server = Server('Pat')    # Embed other objects 
        self.chef   = ProductRobot('Bob')# A robot named bob 
        self.oven   = Oven() 

    def order(self, name): 
        customer = Customer(name)  # Activate other objects 
        customer.order(self.server)# Customer orders from server 
        self.chef.work() 
        self.oven.bake() 
        customer.pay(self.server) 

if __name__ == "__main__": 
    scene = ProductShop()            # Make the composite 
    scene.order('Java')            # Simulate Java's order 
    print('...') 
    scene.order('Javascript')      # Simulate Javascript's order

Result

Related Quiz