I want to create simple applications using builder and prototype patterns to build different houses.
(1) Modifying the program, I added the name self._builder.name()
attribute to the create_house method, which sets the name of the house for us. However, unexpectedly gets an error: AttributeError: 'House1' object has no attribute 'name
'. I have no idea why this is happening since I think I have defined everything correctly.
class Director():
def __init__(self, builder):
self._builder = builder
def create_house(self):
self._builder.name()
self._builder.create_new_house()
self._builder.add_basement()
self._builder.add_rooms()
self._builder.add_roof()
def get_house(self):
return self._builder.house
class Builder():
def __init__(self):
self.house = None
def create_new_house(self):
self.house = House()
class House1(Builder):
def add_name(self):
self.house.name = 'house1'
def add_basement(self):
self.house.basement = 'with basement'
def add_roof(self):
self.house.roof = 'wood roof'
def add_rooms(self):
self.house.rooms = 3
class House2(Builder):
def add_name(self):
self.house.name = 'house2'
def add_basement(self):
self.house.basement = 'no basement'
def add_roof(self):
self.house.roof = 'brick roof'
def add_rooms(self):
self.house.rooms = 5
class House():
def __init__(self):
self.name = None
self.basement = None
self.roof = None
self.rooms = None
def __str__(self):
return 'Building: {} {}, {}, and {} room'.format(self.name, self.basement,
self.roof, self.rooms)
builder = WoodHouse()
director = Director(builder)
director.create_house()
house = director.get_house()
print(house)
(2) by the way, I will ask if I can improve (write less) the process of calling "building" a house. I mean this code, if I create, for example, 3 such houses, I have to repeat it, which is, however, quite unreadable and inconvenient.
builder = WoodHouse()
director = Director(builder)
director.create_house()
house = director.get_house()
print(house)
Aucun commentaire:
Enregistrer un commentaire