模式怎么写

1个回答

写回答

Mingmei啊

2023年01月22日

+ 关注

模式的写法取决于不同的语言和应用场景,以下是一些常见的模式写法示例。

1. 单例模式

Java 示例:

```java

public class Singleton {

private static Singleton instance;

private Singleton() {}

public static Singleton getInstance() {

if (instance == null) {

instance = new Singleton();

}

return instance;

}

}

```

2. 工厂模式

Python 示例:

```python

class Operation:

@staticmethod

def get_result(num1, num2):

pass

class Add(Operation):

@staticmethod

def get_result(num1, num2):

return num1 + num2

class Sub(Operation):

@staticmethod

def get_result(num1, num2):

return num1 - num2

class Mul(Operation):

@staticmethod

def get_result(num1, num2):

return num1 * num2

class Div(Operation):

@staticmethod

def get_result(num1, num2):

if num2 == 0:

raise ValueError('Cannot divide by zero!')

else:

return num1 / num2

class OperationFactory:

@staticmethod

def create_operation(op):

if op == '+':

return Add()

elif op == '-':

return Sub()

elif op == '*':

return Mul()

elif op == '/':

return Div()

else:

raise ValueError('Unsupported operation!')

if __name__ == '__main__':

op_factory = OperationFactory()

operation = op_factory.create_operation('+')

print(operation.get_result(1, 2))

```

3. 观察者模式

C# 示例:

```csharp

using System;

using System.Collections.Generic;

public interface IObserver

{

void Update(T value);

}

public interface IObservable

{

void AddObserver(IObserver observer);

void RemoveObserver(IObserver observer);

void NotifyObservers(T value);

}

public class WeatherData : IObservable

{

private List> observers = new List>();

public void AddObserver(IObserver observer)

{

observers.Add(observer);

}

public void RemoveObserver(IObserver observer)

{

observers.Remove(observer);

}

public void NotifyObservers(float value)

{

foreach (var observer in observers)

{

observer.Update(value);

}

}

public void SetTemperature(float temperature)

{

NotifyObservers(temperature);

}

}

public class TemperatureDisplay : IObserver

{

public void Update(float temperature)

{

Console.WriteLine($"Temperature changed to {temperature}C");

}

}

public class Program

{

static void Main(string[] args)

{

WeatherData weatherData = new WeatherData();

TemperatureDisplay temperatureDisplay = new TemperatureDisplay();

weatherData.AddObserver(temperatureDisplay);

weatherData.SetTemperature(20.0f);

}

}

```

以上是一些常见模式的示例写法,模式不是一成不变的,需要根据具体应用场景做出调整和改进。

举报有用(13分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号