adapter sample pattern

This commit is contained in:
Claudiu Farcas
2021-04-20 08:38:50 +03:00
parent b37771c4f2
commit 3ba755d872
2 changed files with 81 additions and 1 deletions
+5 -1
View File
@@ -7,6 +7,7 @@ using design_patterns.creational.factory;
using design_patterns.creational.facadebuilder;
using design_patterns.creational.singleton;
using design_patterns.creational.prototype;
using design_patterns.structural.adapter;
namespace design_patterns
{
@@ -23,7 +24,10 @@ namespace design_patterns
// await FunctionalBuilderSample.Run();
// await FacadeBuilderSample.Run();
// await SingletonSample.Run();
await PrototypeSample.Run();
// await PrototypeSample.Run();
// structural
await AdapterSample.Run();
}
catch (System.Exception ex)
{
+76
View File
@@ -0,0 +1,76 @@
using System;
using System.Threading.Tasks;
namespace design_patterns.structural.adapter
{
/// <summary>
/// Adapter is a structural design pattern that
/// allows objects with incompatible interfaces to collaborate.
///
/// This is a special object that converts the interface
/// of one object so that another object can understand it.
///
/// An adapter wraps one of the objects to hide the complexity
/// of conversion happening behind the scenes.
/// The wrapped object isnt even aware of the adapter.
///
/// Its very often used in systems based on some legacy code.
/// </summary>
public class AdapterSample
{
public static async Task Run()
{
Console.WriteLine("Structural - Adapter");
var person = new Person {
ID = Guid.NewGuid().ToString(),
Name = "Test person"
};
ExternalService service = new ExternalService();
ExternalServiceAdapter adapter = new ExternalServiceAdapter();
var status = adapter.GetStatus(person, service);
Console.WriteLine($"Status of {status.ID} - {status.PersonStatus}");
}
}
// client DDD models - we don't want to modify their structure
// to match external system and inherit unwanted data and behavior
public class Person {
public string Name { get; set; }
public string ID { get; set; }
}
public class PersonInfo {
public string ID { get; set; }
public string PersonStatus { get; set; }
}
// defined inside client DDD core
// interface for adapting external service
public interface IExternalService {
PersonInfo GetStatus(Person person, ExternalService service);
}
// (legacy) external Service
public class ExternalService {
public string GetPersonStatus(string id) {
return $"Status OK";
}
}
// adapter implementation, we can have
// multiple adapter implementations if needed
public class ExternalServiceAdapter : IExternalService
{
public PersonInfo GetStatus(Person person, ExternalService service)
{
return new PersonInfo {
ID = person.ID,
PersonStatus = service.GetPersonStatus(person.ID)
};
}
}
}