Can anybody explain the concept of pluggable adapter to me with good example? - language-agnostic

Can anybody explain the concept of pluggable adapter to me with good example?

From what I understood from a quick reading of Google results, a pluggable adapter is an adapter that isn't hard-coded against a specific adaptee. On the surface (the adapter's own interface), it's all the same but it can adapt to different adaptees with different interfaces. I found this thread pretty explanatory:
Basically, it allows you to put in an
adapter when the adaptee (receiver)
protocol is not known at compile time
by using reflection. When you create
the adapter instance, you pass it the
name of the adaptee's method to call,
and also any metadata that's necessary
to translate input types. When the
adapter receives a method call of the
target interface, it uses reflection
to call the corresponding method
specified on the adaptee.
And this:
The main responsibility of the Viewer
is to populate a widget from a domain
model without making any assumptions
about domain itself. JFace viewer uses
the Delegating Objects mechanism in
Pluggable Adapter Pattern to implement
the above requirement.
Think of it as a facehugger from Alien; when it hugs a face, all you see is the slimy back of the facehugger. You can poke it with a stick and try to pry off its arms (the adapter interface). But it basically can hug the face of any human (the adaptee), regardless of the face features. Maybe I'm pushing it a bit, but, hey, I love Alien.

You can read this article about adapter/pluggable pattern:
Table of content in this article:
* 1 Design Patterns
* 2 Intent of Adapter
* 3 Motivation
* 4 Structure
* 5 Applicability
* 6 Consequences
* 7 Implementation
o 7.1 Known Uses and Sample Code
o 7.2 Related Patterns
* 8 Conclusions
* 9 Appendix
o 9.1 References
o 9.2 Glossary
Quote:
Smalltalk introduced the concept of a
"pluggable adapter" to describe
classes with built-in interface
adaptation. This interesting concept
allows for classes to be introduced
into existing systems that might
expect different interfaces to the
class. This technique can help promote
class reuse across modules and even
projects.
Here is a small example:
We have two classes - Foo & Boo that outputs some string to console. Adapter class can adapt methods from both classes to provide interface (SaySomething) required by client. Note that there is no dependency on interface name - we can easily adapt both SayHey and Bark methods.
class Foo
{
public static void SayHey() { Console.WriteLine("Hey!"); }
}
class Boo
{
public static void Bark() { Console.WriteLine("Woof!"); }
}
class Adapter
{
public Action SaySomething { get; private set;} // "pluggable" adapter
public Adapter(Action saySomethingAction)
{
SaySomething = saySomethingAction;
}
}
class Program
{
static void Main(string[] args)
{
(new Adapter(Foo.SayHey)).SaySomething();
(new Adapter(Boo.Bark)).SaySomething();
}
}

A distinguish Feature of the Pluggable Adapter is that the method called by the client and the method existing in the interface can be different.
interface Ilegacy
{
float calculate(int a, int b);
}
class Legacy : Ilegacy
{
public float calculate(int a, int b)
{
return a * b;
}
}
class Adapter
{
public Func<int, int, float> legacyCalculator;
public Adapter()
{
this.legacyCalculator = new Legacy().calculate;
}
}
class Client
{
static void Main()
{
float result = new Adapter().legacyCalculator(5, 6);
}
}
This can normally acheived with the use of delegate,Func or Action in C#

Related

SOLID : SRP + ISP

I am trying to understand SOLID principles. I think I understand well the Liskov Substitution Principle, but I have some problems for other ones.
One example. I have two interfaces : Engine and car stereo.
The problem is : For a car, we have 6 glasses.
So, my car implements interfaces Engine and Car Stereo.
But for the 6 glasses, should I implement them, or should I put them on an array of glasses knowing there are 4 laterals glasses which are able to be up or down and 2 windshields (glasses inherited by both).
The problem with the first one is, I can't implement 4 times the same glasses.
So the second one seems to me good but I am afraid that break SRP, I am not sure to understand what "Responsibilities" exactly are.
The correct design practise is to
code to interface rather than class.
In light of this principle I'd recommend to use a interfaces like IWindow, ISurface, IWindShield with a hierarchy like below
interface ISurface
{
//surface specific properties which ideally should be DI-ed
public SurfaceType SurfaceType {get; set;}
public decimal Opacity {get;set;}
public decimal Thickness {get; set;}
}
and
interface IWindow:ISurface
{
//Window behavior specific properties and methods
public void lowerWindow();
public WindowHeight WindowLevel(){get;set;}
public void shutWindow();
// ...and more such window specific behavior
}
and
interface IWindShield:ISurface
{
//WindShield behavior specific properties and methods
public bool IsFogged(){get;set;}
public bool IsClean(){get;set;}
// ...and more such window specific behavior
}
Finally when assembling a car with all its functionality (presumably using a Builder pattern), you can have an array in the Car class of type ISurface type like below
class Car
{
string carName;
Engine carEngine;
Stereo carStereo;
List<ISurface> carGlasses;
.....
// other Car parts
// this is a typical builder pattern example
}
this is build using a CarBuilder type class say MyCarBuilder where
interface CarBuilder
{
public Car MyCar {get; set;}
void AddEngine();
void AddStereo();
void AddGlasses();// this is what works on adding ISurface List items
// and other car building methods
}
and the real builder class
class MyCarBuilder:CarBuilder
{
//... implements all methods of building your custom car
}
It really depends on intended use, but lets take car functional domain (invented on the spot) for example.
Your implementation class will implement IMotor (Tesla D has two motors), IEntertainmentCentre (lets hope there is one), IGlassSurface (could be quite a number in SUV). In each interface you will specify which motor/glass-surface you are addressing, for example: IGlassSurface.Operate(glassSurfaceId, direction, distance).

How to declare static field in class

I have a XAML + DirectX app and I want to add static field to my "interop" class:
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Direct3DInterop sealed : public Windows::Phone::Input::Interop::IDrawingSurfaceManipulationHandler
{
public:
static int VALUE = 0;
...
};
It does not compile saying "only static const integral data members can be initialized within a class".
If I change it to const static int VALUE = 0; then it still does not compile with error "a non-value type cannot have any public data members"
What am I doing wrong?
WinRT public classes have a number of limitations to ensure they are consumable by multiple languages including C++, JavaScript, and C#. This is why you are getting error C3984. You can't have public fields and instead must use properties. You'd make it a read-only property:
property int VALUE
{
int get() { return 0; }
}
It is important to remember that properties are function calls and can't usually be optimized away, so you should consider that when designing the interfaces.
If you intend to have this class only consumable by C++, consider not using a WinRT class and instead use a simple C++ class which you managed the lifetime using std::unique_ptr or std::shared_ptr. In that case, you can of course use the public field approach as always.
The original problem you got is a general C++ language restriction not specific to WinRT. Error C2864 (you are using VS 2012 from the text you posted) is a little more general with C++11 in VS2013.

Custom Neo4j GraphViz Writer

I have an application which produces a GraphViz dot file for a subgraph of my Neo4j database. It works like a charm, but there is somewhat of an issue.
Right now, the title of each node is the node id. Then the properties are listed, with their respective types. This is more information than I need and I would like to change the way the GraphViz writer is configured.
I noticed several classes/interfaces such as GraphStyle, StyleParameter, StyleConfiguration but I've tried several things and keep running into the issue that I cannot access certain classes/interfaces outside of their respective package. Maybe I'm doing it wrong, maybe it's designed so users cannot reconfigure the GraphViz writer, I don't know but I'd like to know.
How do I reconfigure the GraphViz writer so the dot file contains only that information which I want it to contain, namely a property of my choosing as the title, and nothing else as far as the nodes are concerned. Also, this is not always the same property, so for some nodes I'd like property A to be the title, and for nodes that don't have property A, I'd like property B to be the title.
Any help would be greatly appreciated.
You could try using the styles provided by this class: https://github.com/neo4j/neo4j/blob/master/community/graphviz/src/main/java/org/neo4j/visualization/graphviz/AsciiDocSimpleStyle.java
It might be useful to look into this class as well: https://github.com/neo4j/neo4j/blob/master/community/graphviz/src/main/java/org/neo4j/visualization/asciidoc/AsciidocHelper.java
I managed to get it to work. First of all, you need to create two new classes:
class NodeStyleImpl implements NodeStyle
class RelationshipStyleImpl implements RelationshipStyle
Here you can define how nodes and relations should be written in the dot notation. An example implementation looks like this :
public class NodeStyleImpl implements NodeStyle {
public void emitNodeStart(Appendable apndbl, Node node) throws IOException {
apndbl.append(" N" + node.getId() + " [\n label = \"");
}
public void emitEnd(Appendable apndbl) throws IOException {
apndbl.append("\"\n]\n");
}
public void emitProperty(Appendable apndbl, String propkey, Object propvalue) throws IOException {
if(propkey.equals("propkeyone") || propkey.equals("propkeytwo"){
apndbl.append(propvalue.toString());
}
}
}
In an analog fashion, you can write the RelationshipStyleImpl. If you're looking for more advanced configuration, you can also write a StyleConfiguration implementation. You can look at the default implementations in the Neo4j code for an example.
Then there's the issue with the GraphStyle class. The GraphStyle class has a constructor which is protected, thus only accessible from within the package. I made a pull request to change it to public but for the moment, here's a little "hack" which provides a workaround.
package org.neo4j.visualization.graphviz
public class GraphStyleImpl extends GraphStyle {
private GraphStyleImpl (NodeStyleImpl nstyle, RelationshipStyleImpl rstyle) {
super(nstyle, rstyle);
}
}
Note the package declaration. Because the GraphStyle constructor is protected, the super(nstyle, rstyle) method is only accessible from within the same package. By extending the class with a new public constructor, you can now do the following:
GraphStyle graphstyle = new GraphStyleImpl(new NodeStyleImpl(), new RelationshipStyleImpl());
GraphvizWriter writer = new GraphvizWriter(graphstyle);
If my pull request gets accepted, the use of the GraphStyleImpl class will no longer be necessary.

Localization using a DI framework - good idea?

I am working on a web application which I need to localize and internationalize. It occurred to me that I could do this using a dependency injection framework. Let's say I declare an interface ILocalResources (using C# for this example but that's not really important):
interface ILocalResources {
public string OkString { get; }
public string CancelString { get; }
public string WrongPasswordString { get; }
...
}
and create implementations of this interface, one for each language I need to support. I would then setup my DI framework to instantiate the proper implementation, either statically or dynamically (for example based on the requesting browsers preferred language).
Is there some reason I shouldn't be using a DI framework for this sort of thing? The only objection I could find myself is that it might be a bit overkill, but if I'm using a DI framework in my web app anyway, I might as well use it for internationalization as well?
A DI framework is built to do dependency injection and localization could just be one of your services, so in that case there's no reason not to use a DI framework IMO. Perhaps we should start discussing the provided ILocalResources interface. While I'm a favor of having compile time support, I'm not sure the supplied interface will help you, because that interface will be probably the type in your system that will change the most. And with that interface the type/types that implement it. Perhaps you should go with a different design.
When we look at most localization frameworks/providers/factories (or whatever), they're all string based. Because of this, think about the following design:
public interface ILocalResources
{
string GetStringResource(string key);
string GetStringResource(string key, CultureInfo culture);
}
This would allow you to add keys and cultures to the underlying message data store, without changing the interface. Downside is of course that you should never change a key, because that will probably be a hell.
Another approach could be an abstract base type:
public abstract class LocalResources
{
public string OkMessage { get { return this.GetString("OK"); } }
public string CancelMessage { get { return this.GetString("Cancel"); } }
...
protected abstract string GetStringResource(string key,
CultureInfo culture);
private string GetString(string key)
{
Culture culture = CultureInfo.CurrentCulture;
string resource = GetStringResource(key, culture);
// When the resource is not found, fall back to the neutral culture.
while (resource == null && culture != CultureInfo.InvariantCulture)
{
culture = culture.Parent;
resource = this.GetStringResource(key, culture);
}
if (resource == null) throw new KeyNotFoundException(key);
return resource;
}
}
And implementation of this type could look like this:
public sealed class SqlLocalResources : LocalResources
{
protected override string GetStringResource(string key,
CultureInfo culture)
{
using (var db = new LocalResourcesContext())
{
return (
from resource in db.StringResources
where resource.Culture == culture.Name
where resource.Key == key
select resource.Value).FirstOrDefault();
}
}
}
This approach takes best of both worlds, because the keys won't be scattered through the application and adding new properties just has to be done in one single place. Using your favorite DI library, you can register an implementation like this:
container.RegisterSingleton<LocalResources>(new SqlLocalResources());
And since the LocalResources type has exactly one abstract method that does all the work, it is easy to create a decorator that adds caching to prevent requesting the same data from the database:
public sealed class CachedLocalResources : LocalResources
{
private readonly Dictionary<CultureInfo, Dictionary<string, string>> cache =
new Dictionary<CultureInfo, Dictionary<string, string>>();
private readonly LocalResources decoratee;
public CachedLocalResources(LocalResources decoratee) { this.decoratee = decoratee; }
protected override string GetStringResource(string key, CultureInfo culture) {
lock (this.cache) {
string res;
var cultureCache = this.GetCultureCache(culture);
if (!cultureCache.TryGetValue(key, out res)) {
cultureCache[key] = res= this.decoratee.GetStringResource(key, culture);
}
return res;
}
}
private Dictionary<string, string> GetCultureCache(CultureInfo culture) {
Dictionary<string, string> cultureCache;
if (!this.cache.TryGetValue(culture, out cultureCache)) {
this.cache[culture] = cultureCache = new Dictionary<string, string>();
}
return cultureCache;
}
}
You can apply the decorator as follows:
container.RegisterSingleton<LocalResources>(
new CachedLocalResources(new SqlLocalResources()));
Do note that this decorator caches the string resources indefinitely, which might cause memory leaks, so you wish to wrap the strings in WeakReference instances or have some sort of expiration timeout on it. But the idea is that you can apply caching without having to change any existing implementation.
I hope this helps.
If you cannot use an existing resource framework (like that built into ASP.Net) and would have to build your own, I will assume that you at some point will need to expose services that provide localized resources.
DI frameworks are used to handle service instantiation. Your localization framework will expose services providing localization. Why shouldn't that service be served up by the framework?
Not using DI for its purpose here is like saying, "I'm building a CRM app but cannot use DI because DI is not built for customer relations management".
So yes, if you're already using DI in the rest of your application, IMO it would be wrong to not use it for the services handling localization.
The only disadvantage I can see is that for any update to "resources", you would have to recompile the assembly containing resources. And depending on your project, this disadvantage may be a good advise to only use a DI framework for resolving a ResourceService of some kind, rather than the values itself.

Access to global application settings

A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there.
The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database).
This works better, in any case much better than having all those objects need some global Settings object --- that of course effectively makes unit testing impossible :) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects.
So the general question is: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times...
(Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences)
You could use Martin Fowlers ServiceLocator pattern. In php it could look like this:
class ServiceLocator {
private static $soleInstance;
private $globalSettings;
public static function load($locator) {
self::$soleInstance = $locator;
}
public static function globalSettings() {
if (!isset(self::$soleInstance->globalSettings)) {
self::$soleInstance->setGlobalSettings(new GlobalSettings());
}
return self::$soleInstance->globalSettings;
}
}
Your production code then initializes the service locator like this:
ServiceLocator::load(new ServiceLocator());
In your test-code, you insert your mock-settings like this:
ServiceLocator s = new ServiceLocator();
s->setGlobalSettings(new MockGlobalSettings());
ServiceLocator::load(s);
It's a repository for singletons that can be exchanged for testing purposes.
I like to model my configuration access off of the Service Locator pattern. This gives me a single point to get any configuration value that I need and by putting it outside the application in a separate library, it allows reuse and testability. Here is some sample code, I am not sure what language you are using, but I wrote it in C#.
First I create a generic class that will models my ConfigurationItem.
public class ConfigurationItem<T>
{
private T item;
public ConfigurationItem(T item)
{
this.item = item;
}
public T GetValue()
{
return item;
}
}
Then I create a class that exposes public static readonly variables for the configuration item. Here I am just reading the ConnectionStringSettings from a config file, which is just xml. Of course for more items, you can read the values from any source.
public class ConfigurationItems
{
public static ConfigurationItem<ConnectionStringSettings> ConnectionSettings = new ConfigurationItem<ConnectionStringSettings>(RetrieveConnectionString());
private static ConnectionStringSettings RetrieveConnectionString()
{
// In .Net, we store our connection string in the application/web config file.
// We can access those values through the ConfigurationManager class.
return ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["ConnectionKey"]];
}
}
Then when I need a ConfigurationItem for use, I call it like this:
ConfigurationItems.ConnectionSettings.GetValue();
And it will return me a type safe value, which I can then cache or do whatever I want with.
Here's a sample test:
[TestFixture]
public class ConfigurationItemsTest
{
[Test]
public void ShouldBeAbleToAccessConnectionStringSettings()
{
ConnectionStringSettings item = ConfigurationItems.ConnectionSettings.GetValue();
Assert.IsNotNull(item);
}
}
Hope this helps.
Usually this is handled by an ini file or XML configuration file. Then you just have a class that reads the setting when neeed.
.NET has this built in with the ConfigurationManager classes, but it's quite easy to implement, just read text files, or load XML into DOM or parse them by hand in code.
Having config files in the database is ok, but it does tie you to the database, and creates an extra dependancy for your app that ini/xml files solve.
I did this:
public class MySettings
{
public static double Setting1
{ get { return SettingsCache.Instance.GetDouble("Setting1"); } }
public static string Setting2
{ get { return SettingsCache.Instance.GetString("Setting2"); } }
}
I put this in a separate infrastructure module to remove any issues with circular dependencies.
Doing this I am not tied to any specific configuration method, and have no strings running havoc in my applications code.