AIGC提示词:生成设计模式代码示例
2023-06-29 14:55 更新
使用场景: 设计模式实现
中文提示词
在{language}中,关于{design_pattern}设计模式的代码示例?
示例对话
ChatGPT3.5 设计模式实现
用户
在{language}中,关于{design_pattern}设计模式的代码示例?
AI模型(ChatGPT3.5)
在中文中,关于设计模式的代码示例:
### 单例模式
```python
## 单例模式示例
class Singleton(object):
__instance = None
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = super().__new__(cls, *args, **kwargs)
return cls.__instance
s1 = Singleton()
s2 = Singleton()
print(s1 == s2) # True
工厂模式
## 工厂模式示例
class Animal(object):
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Cat(Animal):
def speak(self):
return 'meow'
class Dog(Animal):
def speak(self):
return 'woof'
class AnimalFactory(object):
@staticmethod
def create_animal(kind):
if kind == 'cat':
return Cat('Kitty')
elif kind == 'dog':
return Dog('Fido')
else:
return None
cat = AnimalFactory.create_animal('cat')
print(cat.name)
print(cat.speak())
---