23种常用架构风格
23种常用架构风格
本文23种架构风格,并给出相应的C#代码示例以及代码中体现该风格的点:
1. 分层架构风格
分层架构将系统划分为多个层次,每层有特定的职责。常见的有表示层、业务逻辑层、数据访问层等。
// 数据访问层
public class DataAccessLayer
{
public string GetData()
{
return "Data from database";
}
}
// 业务逻辑层
public class BusinessLogicLayer
{
private DataAccessLayer dataAccessLayer;
public BusinessLogicLayer()
{
dataAccessLayer = new DataAccessLayer();
}
public string ProcessData()
{
string data = dataAccessLayer.GetData();
return $"Processed: {data}";
}
}
// 表示层
public class PresentationLayer
{
private BusinessLogicLayer businessLogicLayer;
public PresentationLayer()
{
businessLogicLayer = new BusinessLogicLayer();
}
public void DisplayData()
{
string result = businessLogicLayer.ProcessData();
Console.WriteLine(result);
}
}
class Program
{
static void Main()
{
PresentationLayer presentation = new PresentationLayer();
presentation.DisplayData();
}
}
体现该风格的点:代码清晰地划分了数据访问层、业务逻辑层和表示层,每层的职责明确,上层依赖下层提供的服务。
2. 客户端 - 服务器架构风格
客户端向服务器请求服务,服务器处理请求并返回结果。
// 服务器端
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Server
{
static void Main()
{
TcpListener server = new TcpListener(IPAddress.Any, 8888);
server.Start();
Console.WriteLine("Server started. Waiting for connections...");
while (true)
{
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string request = Encoding.ASCII.GetString(buffer, 0, bytesRead);
string response = $"Server received: {request}";
byte[] data = Encoding.ASCII.GetBytes(response);
stream.Write(data, 0, data.Length);
client.Close();
}
}
}
// 客户端
using System;
using System.Net.Sockets;
using System.Text;
class Client
{
static void Main()
{
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 8888);
NetworkStream stream = client.GetStream();
string message = "Hello, server!";
byte[] data = Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine(response);
client.Close();
}
}
体现该风格的点:代码分为服务器端和客户端,客户端发起请求,服务器接收请求并返回响应。
3. 主从架构风格
主节点负责协调和控制,从节点执行主节点分配的任务。
// 主节点
using System;
using System.Collections.Generic;
class Master
{
private List<Slave> slaves;
public Master()
{
slaves = new List<Slave>();
}
public void AddSlave(Slave slave)
{
slaves.Add(slave);
}
public void AssignTask(string task)
{
foreach (Slave slave in slaves)
{
slave.ExecuteTask(task);
}
}
}
// 从节点
class Slave
{
public void ExecuteTask(string task)
{
Console.WriteLine($"Slave executing task: {task}");
}
}
class Program
{
static void Main()
{
Master master = new Master();
Slave slave1 = new Slave();
Slave slave2 = new Slave();
master.AddSlave(slave1);
master.AddSlave(slave2);
master.AssignTask("Process data");
}
}
体现该风格的点:Master
类作为主节点,负责添加从节点和分配任务,Slave
类作为从节点,执行主节点分配的任务。
4. 管道 - 过滤器架构风格
数据通过一系列过滤器进行处理,每个过滤器完成特定的处理任务。
using System;
using System.Collections.Generic;
// 过滤器接口
interface IFilter
{
string Process(string input);
}
// 具体过滤器
class UpperCaseFilter : IFilter
{
public string Process(string input)
{
return input.ToUpper();
}
}
class ReverseFilter : IFilter
{
public string Process(string input)
{
char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
// 管道
class Pipeline
{
private List<IFilter> filters;
public Pipeline()
{
filters = new List<IFilter>();
}
public void AddFilter(IFilter filter)
{
filters.Add(filter);
}
public string Process(string input)
{
string output = input;
foreach (IFilter filter in filters)
{
output = filter.Process(output);
}
return output;
}
}
class Program
{
static void Main()
{
Pipeline pipeline = new Pipeline();
pipeline.AddFilter(new UpperCaseFilter());
pipeline.AddFilter(new ReverseFilter());
string result = pipeline.Process("hello");
Console.WriteLine(result);
}
}
体现该风格的点:代码中定义了过滤器接口和具体过滤器,数据依次通过各个过滤器进行处理,形成一个管道。
5. 代理架构风格
代理对象代表另一个对象进行操作,可用于控制访问、增强功能等。
// 真实主题接口
interface ISubject
{
void Request();
}
// 真实主题
class RealSubject : ISubject
{
public void Request()
{
Console.WriteLine("RealSubject: Handling request.");
}
}
// 代理
class Proxy : ISubject
{
private RealSubject realSubject;
public Proxy(RealSubject realSubject)
{
this.realSubject = realSubject;
}
public void Request()
{
if (CheckAccess())
{
realSubject.Request();
LogAccess();
}
}
private bool CheckAccess()
{
Console.WriteLine("Proxy: Checking access prior to firing a real request.");
return true;
}
private void LogAccess()
{
Console.WriteLine("Proxy: Logging the time of request.");
}
}
class Program
{
static void Main()
{
RealSubject realSubject = new RealSubject();
Proxy proxy = new Proxy(realSubject);
proxy.Request();
}
}
体现该风格的点:Proxy
类作为代理,控制对 RealSubject
的访问,并在访问前后执行额外的操作。
6. 事件驱动架构风格
系统通过事件的发布和订阅来进行组件间的通信。
using System;
// 事件发布者
class EventPublisher
{
public event EventHandler<string> EventOccurred;
public void RaiseEvent(string message)
{
EventOccurred?.Invoke(this, message);
}
}
// 事件订阅者
class EventSubscriber
{
public EventSubscriber(EventPublisher publisher)
{
publisher.EventOccurred += HandleEvent;
}
private void HandleEvent(object sender, string message)
{
Console.WriteLine($"Event received: {message}");
}
}
class Program
{
static void Main()
{
EventPublisher publisher = new EventPublisher();
EventSubscriber subscriber = new EventSubscriber(publisher);
publisher.RaiseEvent("An event has occurred!");
}
}
体现该风格的点:EventPublisher
类发布事件,EventSubscriber
类订阅事件,当事件发生时,订阅者会收到通知并执行相应的处理方法。
7. 微内核架构风格
微内核提供核心服务,其他功能以插件形式添加。
using System;
using System.Collections.Generic;
// 微内核接口
interface IMicroKernel
{
void RegisterPlugin(IPlugin plugin);
void ExecutePlugins();
}
// 插件接口
interface IPlugin
{
void Execute();
}
// 微内核实现
class MicroKernel : IMicroKernel
{
private List<IPlugin> plugins;
public MicroKernel()
{
plugins = new List<IPlugin>();
}
public void RegisterPlugin(IPlugin plugin)
{
plugins.Add(plugin);
}
public void ExecutePlugins()
{
foreach (IPlugin plugin in plugins)
{
plugin.Execute();
}
}
}
// 具体插件
class SamplePlugin : IPlugin
{
public void Execute()
{
Console.WriteLine("Sample plugin executed.");
}
}
class Program
{
static void Main()
{
MicroKernel kernel = new MicroKernel();
SamplePlugin plugin = new SamplePlugin();
kernel.RegisterPlugin(plugin);
kernel.ExecutePlugins();
}
}
体现该风格的点:MicroKernel
类作为微内核,负责管理插件的注册和执行,SamplePlugin
类作为插件,实现了具体的功能。
8. 仓库架构风格
仓库负责管理数据的存储和访问。
using System;
using System.Collections.Generic;
// 实体类
class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
// 仓库接口
interface IProductRepository
{
void Add(Product product);
Product GetById(int id);
}
// 仓库实现
class ProductRepository : IProductRepository
{
private List<Product> products;
public ProductRepository()
{
products = new List<Product>();
}
public void Add(Product product)
{
products.Add(product);
}
public Product GetById(int id)
{
return products.Find(p => p.Id == id);
}
}
class Program
{
static void Main()
{
IProductRepository repository = new ProductRepository();
Product product = new Product { Id = 1, Name = "Sample Product" };
repository.Add(product);
Product retrievedProduct = repository.GetById(1);
Console.WriteLine($"Retrieved product: {retrievedProduct.Name}");
}
}
体现该风格的点:ProductRepository
类作为仓库,负责 Product
实体的存储和访问,提供了添加和查询的方法。
9. 黑板架构风格
黑板是一个共享的数据结构,多个知识源可以在上面读写数据。
using System;
using System.Collections.Generic;
// 黑板
class Blackboard
{
private Dictionary<string, object> data;
public Blackboard()
{
data = new Dictionary<string, object>();
}
public void Write(string key, object value)
{
data[key] = value;
}
public object Read(string key)
{
if (data.ContainsKey(key))
{
return data[key];
}
return null;
}
}
// 知识源
class KnowledgeSource
{
private Blackboard blackboard;
public KnowledgeSource(Blackboard blackboard)
{
this.blackboard = blackboard;
}
public void WriteData()
{
blackboard.Write("message", "Data from knowledge source");
}
public void ReadData()
{
object data = blackboard.Read("message");
if (data != null)
{
Console.WriteLine($"Read data: {data}");
}
}
}
class Program
{
static void Main()
{
Blackboard blackboard = new Blackboard();
KnowledgeSource source = new KnowledgeSource(blackboard);
source.WriteData();
source.ReadData();
}
}
体现该风格的点:Blackboard
类作为黑板,提供了读写数据的方法,KnowledgeSource
类作为知识源,可以在黑板上读写数据。
10. 模型 - 视图 - 控制器(MVC)架构风格
将应用程序分为模型(数据和业务逻辑)、视图(用户界面)和控制器(处理用户输入和协调模型与视图)。
using System;
// 模型
class Model
{
public string Data { get; set; }
}
// 视图
class View
{
public void DisplayData(string data)
{
Console.WriteLine($"Displaying data: {data}");
}
}
// 控制器
class Controller
{
private Model model;
private View view;
public Controller(Model model, View view)
{
this.model = model;
this.view = view;
}
public void UpdateModel(string newData)
{
model.Data = newData;
UpdateView();
}
public void UpdateView()
{
view.DisplayData(model.Data);
}
}
class Program
{
static void Main()
{
Model model = new Model();
View view = new View();
Controller controller = new Controller(model, view);
controller.UpdateModel("New data");
}
}
体现该风格的点:代码清晰地划分了模型、视图和控制器,控制器负责协调模型和视图之间的交互。
11. 模型 - 视图 - 呈现器(MVP)架构风格
类似于 MVC,但呈现器负责处理视图和模型之间的交互。
using System;
// 模型
class Model
{
public string Data { get; set; }
}
// 视图接口
interface IView
{
string GetInput();
void DisplayData(string data);
}
// 视图实现
class View : IView
{
public string GetInput()
{
Console.Write("Enter data: ");
return Console.ReadLine();
}
public void DisplayData(string data)
{
Console.WriteLine($"Displaying data: {data}");
}
}
// 呈现器
class Presenter
{
private Model model;
private IView view;
public Presenter(Model model, IView view)
{
this.model = model;
this.view = view;
}
public void UpdateModel()
{
string input = view.GetInput();
model.Data = input;
view.DisplayData(model.Data);
}
}
class Program
{
static void Main()
{
Model model = new Model();
IView view = new View();
Presenter presenter = new Presenter(model, view);
presenter.UpdateModel();
}
}
体现该风格的点:Presenter
类负责处理 View
和 Model
之间的交互,视图只负责显示和获取用户输入。
12. 模型 - 视图 - 视图模型(MVVM)架构风格
通过视图模型实现视图和模型的分离,使用数据绑定机制。
using System.ComponentModel;
// 模型
class Model
{
public string Data { get; set; }
}
// 视图模型
class ViewModel : INotifyPropertyChanged
{
private Model model;
private string displayData;
public string DisplayData
{
get { return displayData; }
set
{
if (displayData != value)
{
displayData = value;
OnPropertyChanged(nameof(DisplayData));
}
}
}
public ViewModel(Model model)
{
this.model = model;
UpdateDisplayData();
}
public void UpdateModel(string newData)
{
model.Data = newData;
UpdateDisplayData();
}
private void UpdateDisplayData()
{
DisplayData = model.Data;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
// 视图
class View
{
private ViewModel viewModel;
public View(ViewModel viewModel)
{
this.viewModel = viewModel;
viewModel.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == nameof(ViewModel.DisplayData))
{
DisplayData(viewModel.DisplayData);
}
};
}
public void UpdateModel(string newData)
{
viewModel.UpdateModel(newData);
}
public void DisplayData(string data)
{
Console.WriteLine($"Displaying data: {data}");
}
}
class Program
{
static void Main()
{
Model model = new Model();
ViewModel viewModel = new ViewModel(model);
View view = new View(viewModel);
view.UpdateModel("New data");
}
}
体现该风格的点:ViewModel
类实现了数据绑定,当模型数据变化时,会通知视图更新显示。
13. 六边形架构风格
将应用程序分为内部核心(业务逻辑)和外部适配器(与外部系统交互)。
// 领域模型
class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
// 端口接口
interface IProductRepository
{
Product GetProductById(int id);
}
// 外部适配器
class InMemoryProductRepository : IProductRepository
{
public Product GetProductById(int id)
{
return new Product { Id = id, Name = "Sample Product" };
}
}
// 应用服务
class ProductService
{
private IProductRepository productRepository;
public ProductService(IProductRepository productRepository)
{
this.productRepository = productRepository;
}
public Product GetProduct(int id)
{
return productRepository.GetProductById(id);
}
}
class Program
{
static void Main()
{
IProductRepository repository = new InMemoryProductRepository();
ProductService service = new ProductService(repository);
Product product = service.GetProduct(1);
Console.WriteLine($"Product name: {product.Name}");
}
}
体现该风格的点:ProductService
类作为应用服务,依赖于 IProductRepository
端口接口,InMemoryProductRepository
类作为外部适配器,实现了端口接口。
14. 事件溯源架构风格
系统通过记录所有发生的事件来重建状态。
using System;
using System.Collections.Generic;
// 事件基类
abstract class Event
{
public DateTime Timestamp { get; set; }
public Event()
{
Timestamp = DateTime.Now;
}
}
// 具体事件
class ProductCreatedEvent : Event
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
// 聚合根
class ProductAggregate
{
private List<Event> events;
public int ProductId { get; private set; }
public string ProductName { get; private set; }
public ProductAggregate()
{
events = new List<Event>();
}
public void CreateProduct(int id, string name)
{
ProductCreatedEvent @event = new ProductCreatedEvent
{
ProductId = id,
ProductName = name
};
ApplyEvent(@event);
events.Add(@event);
}
private void ApplyEvent(Event @event)
{
if (@event is ProductCreatedEvent productCreatedEvent)
{
ProductId = productCreatedEvent.ProductId;
ProductName = productCreatedEvent.ProductName;
}
}
public void ReplayEvents(List<Event> storedEvents)
{
foreach (Event @event in storedEvents)
{
ApplyEvent(@event);
}
}
}
class Program
{
static void Main()
{
ProductAggregate product = new ProductAggregate();
product.CreateProduct(1, "Sample Product");
List<Event> storedEvents = new List<Event> { new ProductCreatedEvent { ProductId = 1, ProductName = "Sample Product" } };
ProductAggregate replayedProduct = new ProductAggregate();
replayedProduct.ReplayEvents(storedEvents);
Console.WriteLine($"Replayed product name: {replayedProduct.ProductName}");
}
}
体现该风格的点:ProductAggregate
类通过记录 ProductCreatedEvent
事件来创建产品,并可以通过重放事件来重建状态。
15. 云计算架构风格
利用云计算平台提供的服务构建系统。以下是一个简单的模拟云存储服务的示例。
using System;
using System.Collections.Generic;
// 云存储服务接口
interface ICloudStorageService
{
void UploadFile(string fileName, string content);
string DownloadFile(string fileName);
}
// 云存储服务实现
class CloudStorageService : ICloudStorageService
{
private Dictionary<string, string> storage;
public CloudStorageService()
{
storage = new Dictionary<string, string>();
}
public void UploadFile(string fileName, string content)
{
storage[fileName] = content;
Console.WriteLine($"File {fileName} uploaded successfully.");
}
public string DownloadFile(string fileName)
{
if (storage.ContainsKey(fileName))
{
return storage[fileName];
}
return null;
}
}
// 客户端应用
class ClientApp
{
private ICloudStorageService cloudStorageService;
public ClientApp(ICloudStorageService cloudStorageService)
{
this.cloudStorageService = cloudStorageService;
}
public void UploadData()
{
cloudStorageService.UploadFile("test.txt", "Sample data");
}
public void DownloadData()
{
string content = cloudStorageService.DownloadFile("test.txt");
if (content != null)
{
Console.WriteLine($"Downloaded content: {content}");
}
else
{
Console.WriteLine("File not found.");
}
}
}
class Program
{
static void Main()
{
ICloudStorageService storageService = new CloudStorageService();
ClientApp client = new ClientApp(storageService);
client.UploadData();
client.DownloadData();
}
}
体现该风格的点:代码模拟了云存储服务,客户端应用通过调用云存储服务接口来上传和下载文件。
16. 无服务器架构风格
使用云服务提供商的无服务器计算服务,如 AWS Lambda、Azure Functions 等。以下是一个简单的模拟无服务器函数的示例。
using System;
// 无服务器函数
class ServerlessFunction
{
public string Execute(string input)
{
return $"Processed: {input}";
}
}
class Program
{
static void Main()
{
ServerlessFunction function = new ServerlessFunction();
string result = function.Execute("Hello");
Console.WriteLine(result);
}
}
体现该风格的点:ServerlessFunction
类模拟了一个无服务器函数,接收输入并返回处理结果,无需管理服务器基础设施。
17. 网格计算架构风格
将多个计算资源连接成一个网格,共同完成计算任务。以下是一个简单的模拟网格计算的示例。
using System;
using System.Collections.Generic;
// 计算节点
class ComputeNode
{
public int ProcessTask(int input)
{
return input * 2;
}
}
// 网格管理器
class GridManager
{
private List<ComputeNode> nodes;
public GridManager()
{
nodes = new List<ComputeNode>();
}
public void AddNode(ComputeNode node)
{
nodes.Add(node);
}
public int ProcessTask(int input)
{
int result = 0;
foreach (ComputeNode node in nodes)
{
result += node.ProcessTask(input);
}
return result;
}
}
class Program
{
static void Main()
{
GridManager gridManager = new GridManager();
ComputeNode node1 = new ComputeNode();
ComputeNode node2 = new ComputeNode();
gridManager.AddNode(node1);
gridManager.AddNode(node2);
int taskResult = gridManager.ProcessTask(5);
Console.WriteLine($"Task result: {taskResult}");
}
}
体现该风格的点:GridManager
类管理多个 ComputeNode
计算节点,将计算任务分配给各个节点并汇总结果。
18. 对等网络(P2P)架构风格
节点之间直接通信和共享资源。以下是一个简单的模拟 P2P 网络的示例。
using System;
using System.Collections.Generic;
// 节点
class PeerNode
{
private string nodeId;
private Dictionary<string, PeerNode> peers;
public PeerNode(string nodeId)
{
this.nodeId = nodeId;
peers = new Dictionary<string, PeerNode>();
}
public void ConnectToPeer(PeerNode peer)
{
peers[peer.nodeId] = peer;
Console.WriteLine($"Node {nodeId} connected to node {peer.nodeId}");
}
public void SendMessage(string peerId, string message)
{
if (peers.ContainsKey(peerId))
{
peers[peerId].ReceiveMessage(nodeId, message);
}
else
{
Console.WriteLine($"Node {peerId} not found.");
}
}
public void ReceiveMessage(string senderId, string message)
{
Console.WriteLine($"Node {nodeId} received message from node {senderId}: {message}");
}
}
class Program
{
static void Main()
{
PeerNode node1 = new PeerNode("Node1");
PeerNode node2 = new PeerNode("Node2");
node1.ConnectToPeer(node2);
node1.SendMessage("Node2", "Hello!");
}
}
体现该风格的点:PeerNode
类代表 P2P 网络中的节点,节点之间可以直接连接和发送消息。
19. 基于组件的架构风格
系统由多个可复用的组件组成。以下是一个简单的模拟组件化系统的示例。
// 组件接口
interface IComponent
{
void Execute();
}
// 具体组件
class ComponentA : IComponent
{
public void Execute()
{
Console.WriteLine("Component A executed.");
}
}
class ComponentB : IComponent
{
public void Execute()
{
Console.WriteLine("Component B executed.");
}
}
// 系统
class System
{
private List<IComponent> components;
public System()
{
components = new List<IComponent>();
}
public void AddComponent(IComponent component)
{
components.Add(component);
}
public void Run()
{
foreach (IComponent component in components)
{
component.Execute();
}
}
}
class Program
{
static void Main()
{
System system = new System();
ComponentA componentA = new ComponentA();
ComponentB componentB = new ComponentB();
system.AddComponent(componentA);
system.AddComponent(componentB);
system.Run();
}
}
体现该风格的点:代码中定义了组件接口和具体组件,System
类管理多个组件,并可以运行所有组件。
20. 基于服务的架构风格
系统由多个服务组成,服务之间通过接口进行通信。以下是一个简单的模拟服务化系统的示例。
// 服务接口
interface IService
{
string Process(string input);
}
// 具体服务
class ServiceA : IService
{
public string Process(string input)
{
return $"Service A processed: {input}";
}
}
class ServiceB : IService
{
public string Process(string input)
{
return $"Service B processed: {input}";
}
}
// 服务管理器
class ServiceManager
{
private Dictionary<string, IService> services;
public ServiceManager()
{
services = new Dictionary<string, IService>();
}
public void RegisterService(string serviceName, IService service)
{
services[serviceName] = service;
}
public string InvokeService(string serviceName, string input)
{
if (services.ContainsKey(serviceName))
{
return services[serviceName].Process(input);
}
return null;
}
}
class Program
{
static void Main()
{
ServiceManager manager = new ServiceManager();
ServiceA serviceA = new ServiceA();
ServiceB serviceB = new ServiceB();
manager.RegisterService("ServiceA", serviceA);
manager.RegisterService("ServiceB", serviceB);
string resultA = manager.InvokeService("ServiceA", "Hello");
string resultB = manager.InvokeService("ServiceB", "World");
Console.WriteLine(resultA);
Console.WriteLine(resultB);
}
}
体现该风格的点:代码中定义了服务接口和具体服务,ServiceManager
类管理多个服务,并可以调用服务的方法。
21. 面向服务的架构(SOA)风格
强调服务的松散耦合、可重用性和互操作性。以下是一个简单的模拟 SOA 系统的示例。
// 服务契约
interface IProductService
{
string GetProductName(int productId);
}
// 服务实现
class ProductService : IProductService
{
public string GetProductName(int productId)
{
return $"Product {productId} name";
}
}
// 服务消费者
class ServiceConsumer
{
private IProductService productService;
public ServiceConsumer(IProductService productService)
{
this.productService = productService;
}
public void DisplayProductName(int productId)
{
string name = productService.GetProductName(productId);
Console.WriteLine(name);
}
}
class Program
{
static void Main()
{
IProductService productService = new ProductService();
ServiceConsumer consumer = new ServiceConsumer(productService);
consumer.DisplayProductName(1);
}
}
体现该风格的点:代码中定义了服务契约和服务实现,服务消费者通过服务契约调用服务,实现了服务的松散耦合。
22. 微服务架构风格
将应用程序拆分为多个小型、自治的服务。以下是一个简单的模拟微服务系统的示例。
// 订单服务
class OrderService
{
public string CreateOrder()
{
return "Order created";
}
}
// 库存服务
class InventoryService
{
public bool CheckStock()
{
return true;
}
}
// 客户服务
class CustomerService
{
public string GetCustomerInfo(int customerId)
{
return $"Customer {customerId} info";
}
}
// 业务流程
class BusinessProcess
{
private OrderService orderService;
private InventoryService inventoryService;
private CustomerService customerService;
public BusinessProcess()
{
orderService = new OrderService();
inventoryService = new InventoryService();
customerService = new CustomerService();
}
public void PlaceOrder(int customerId)
{
if (inventoryService.CheckStock())
{
string orderResult = orderService.CreateOrder();
string customerInfo = customerService.GetCustomerInfo(customerId);
Console.WriteLine($"{orderResult}, Customer info: {customerInfo}");
}
else
{
Console.WriteLine("No stock available.");
}
}
}
class Program
{
static void Main()
{
BusinessProcess process = new BusinessProcess();
process.PlaceOrder(1);
}
}
体现该风格的点:代码将应用程序拆分为订单服务、库存服务和客户服务三个微服务,BusinessProcess
类协调各个微服务完成业务流程。
23. 区块链架构风格
基于区块链技术构建的分布式系统。以下是一个简单的模拟区块链的示例。
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
// 区块
class Block
{
public int Index { get; set; }
public DateTime Timestamp { get; set; }
public string Data { get; set; }
public string PreviousHash { get; set; }
public string Hash { get; set; }
public Block(int index, string data, string previousHash)
{
Index = index;
Timestamp = DateTime.Now;
Data = data;
PreviousHash = previousHash;
Hash = CalculateHash();
}
public string CalculateHash()
{
using (SHA256 sha256Hash = SHA256.Create())
{
string input = Index + Timestamp.ToString() + Data + PreviousHash;
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
}
// 区块链
class Blockchain
{
public List<Block> Chain { get; set; }
public Blockchain()
{
Chain = new List<Block>();
CreateGenesisBlock();
}
public void CreateGenesisBlock()
{
Block genesisBlock = new Block(0, "Genesis Block", "0");
Chain.Add(genesisBlock);
}
public Block GetLatestBlock()
{
return Chain[Chain.Count - 1];
}
public void AddBlock(Block newBlock)
{
newBlock.PreviousHash = GetLatestBlock().Hash;
newBlock.Hash = newBlock.CalculateHash();
Chain.Add(newBlock);
}
public bool IsChainValid()
{
for (int i = 1; i < Chain.Count; i++)
{
Block currentBlock = Chain[i];
Block previousBlock = Chain[i - 1];
if (currentBlock.Hash != currentBlock.CalculateHash())
{
return false;
}
if (currentBlock.PreviousHash != previousBlock.Hash)
{
return false;
}
}
return true;
}
}
class Program
{
static void Main()
{
Blockchain blockchain = new Blockchain();
blockchain.AddBlock(new Block(1, "Transaction Data 1", ""));
blockchain.AddBlock(new Block(2, "Transaction Data 2", ""));
Console.WriteLine("Is blockchain valid? " + blockchain.IsChainValid());
}
}