简单工厂模式,工厂工厂模式,抽象工厂模式的示例代码实现
时间: 2023-06-12 16:08:17 浏览: 120
简单工厂模式、工厂模式、抽象工厂模式案例(C++实现)
5星 · 资源好评率100%
以下是三种工厂模式的示例代码实现:
1. 简单工厂模式:
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow"
class AnimalFactory:
def create_animal(self, name, animal_type):
if animal_type == "dog":
return Dog(name)
elif animal_type == "cat":
return Cat(name)
else:
return None
factory = AnimalFactory()
dog = factory.create_animal("Buddy", "dog")
cat = factory.create_animal("Misty", "cat")
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow
```
2. 工厂方法模式:
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow"
class AnimalFactory:
def create_animal(self, name):
pass
class DogFactory(AnimalFactory):
def create_animal(self, name):
return Dog(name)
class CatFactory(AnimalFactory):
def create_animal(self, name):
return Cat(name)
dog_factory = DogFactory()
cat_factory = CatFactory()
dog = dog_factory.create_animal("Buddy")
cat = cat_factory.create_animal("Misty")
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow
```
3. 抽象工厂模式:
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow"
class AnimalFactory:
def create_dog(self, name):
pass
def create_cat(self, name):
pass
class DogFactory(AnimalFactory):
def create_dog(self, name):
return Dog(name)
class CatFactory(AnimalFactory):
def create_cat(self, name):
return Cat(name)
class PetStore:
def __init__(self, animal_factory):
self.animal_factory = animal_factory
def buy_dog(self, name):
return self.animal_factory.create_dog(name)
def buy_cat(self, name):
return self.animal_factory.create_cat(name)
dog_factory = DogFactory()
cat_factory = CatFactory()
pet_store = PetStore(dog_factory)
dog = pet_store.buy_dog("Buddy")
print(dog.speak()) # Output: Woof!
pet_store = PetStore(cat_factory)
cat = pet_store.buy_cat("Misty")
print(cat.speak()) # Output: Meow
```
阅读全文