Overriding an internal method with Decorator Design Pattern - oop

I am writing an object-oriented code in which I am trying to use Decorator pattern to implement a variety of optimizations to be applied on a family of core classes at runtime. The main behaviour of core classes is a complex behaviour that is fully implemented in those classes, which indeed calls other internal methods to fulfill pieces of the task.
The decorators will only customize the internal methods which are called by the complex behaviour in core class.
Here is a pseudo-code of what I'm trying to reach:
interface I{
complex();
step1();
step2();
}
class C implements I{
complex(){
...
this.step1();
...
this.step2();
}
step1(){
...
}
step2(){
...
}
}
abstract class Decorator implements I{
I wrapped;
constructor(I obj){
this.wrapped = obj;
}
complex(){
this.wrapped.complex();
}
step1(){
this.wrapped.step1();
}
step2(){
this.wrapped.step2();
}
}
class ConcreteDecorator extends Decorator{
constructor(I obj){
super(obj);
}
step2(){
... // customizing step2()
}
}
There are a variety of customizations possible which could be combined together, and that is the main reason I'm using decorator pattern. otherwise I'll get to create dozens to hundred subtypes for each possible combination of customizations.
Now if I try to create object of the decorated class:
x = new C();
y = new ConcreteDecorator(x);
y.complex();
I expect the complex() method to be executed form the wrapped core object, while using the overridden step2() method from decorator. But it does not work this way as the complex() method in abstract decorator directly calls the method on core object which indeed skips the overridden step2() in decorator.
My overall goal is to enable the decorators only overriding one or few of the stepx() methods and that would be invoked by the complex() method which is already implemented in the core object and invokes all the steps.
Could this functionality be implemented using Decorator design pattern at all? If yes how, and if not what is the appropriate design pattern for tackling this problem.
Thanks.

I guess you could resolve that problem with Strategy pattern, where the Strategy interface includes the methods that are vary from class to class. Strategy interface may include as only one method as well as several depending on their nature.
interface IStrategy {
step1(IData data);
step2(IData data);
}
interface I {
complex();
}
class C implements I {
IData data
constructor(IStrategy strategy) {}
complex() {
...
this.strategy.step1(this.data);
...
this.strategy.step2(this.data);
}
}
class S1 implements IStrategy {
constructor(IStrategy strategy)
step1(IData data) {
}
step2(IData data) {
}
}
strategy1 = new S1();
c = new C(strategy1)

The issue you are facing is that in your application of the Decorator design pattern, because you are not decorating complex(), the call to complex() on a decorator object will be delegated to the decorated object, which has "normal" version of step2.
I think a more appropriate design pattern to solve your problem would be the Template Method design pattern.
In your case complex() would play the role of the template method, whose steps can be customized by subclasses. Instead of using composition, you use inheritance, and the rest stays more or less the same.
Here is a sample application of the Template Method design pattern to your context:
public interface I {
void complex();
void step1(); // Better to remove from the interface if possible
void step2(); // Better to remove from the interface if possible
}
// Does not need to be abstract, but can be
class DefaultBehavior implements I {
// Note how this is final to avoid having subclass
// change the algorithm.
public final void complex() {
this.step1();
this.step2();
}
public void step1() { // Default step 1
System.out.println("Default step 1");
}
public void step2() { // Default step 2
System.out.println("Default step 1");
}
}
class CustomizedStep2 extends DefaultBehavior {
public void step2() { // Customized step 2
System.out.println("Customized step 2");
}
}

Related

Util class in Kotlin (Best Approach)? [duplicate]

This question already has answers here:
Utils class in Kotlin
(3 answers)
Closed 1 year ago.
I was playing with Kotlin, and creating Util class with different ways. I am approaching a way that works best for calling by either Kotlin or Java.
Now I have created many types of Util. And now I am very confused which is best to use and most important why? I am finding best way considering Heap, Memory, Performance.
My question may look stupid for you guys, but I am in maze and can't come to a solution myself.
Here is my playground.
I have created 5 Kotlin files. in which I have put foo() method. and tried to call by Kotlin and Java.
Calling class Bar.kt
class Bar {
fun bazz() {
UtilClass.instance.foo()
UtilClassObject.UtilClassObject.foo()
UtilCompanionObject.foo()
UtilFileObject.foo()
foo() // from UtilFile
}
}
Calling class Qux.java
public class Qux {
public void bazz() {
UtilClass.Companion.getInstance().foo();
UtilClassObject.UtilClassObject.INSTANCE.foo();
UtilFileKt.foo();
UtilFileObject.INSTANCE.foo();
UtilCompanionObject.Companion.foo();
}
}
And here is the maze that makes me confused to choose best.
UtilClass.kt
class UtilClass {
fun foo() { ... }
companion object {
val instance = UtilClass()
}
}
UtilClassObject.kt
class UtilClassObject {
object UtilClassObject {
fun foo() { ... }
}
}
UtilCompanionObject.kt
class UtilCompanionObject {
companion object {
fun foo() { ... }
}
}
UtilFile.kt
fun foo(){ ... }
UtilFileObject.kt
object UtilFileObject {
fun foo() { ... }
}
It may take to answer my question and explaining it well. So I really appreciate your efforts in advance.
All options are present on the Kotlin reference page for interop between Kotlin and Java: https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html
Your options to call from Java something on class MyUtil and call it without an instance such as MyUtil.foo() then you would simply do one of the two options:
// smallest byte code,
// static invocation of foo() from Kotlin side,
// also static call from Java to foo()
object MyUtil {
#JvmStatic fun foo() { ... }
}
or
// creates two classes,
// static lookup of companion followed by virtual call on that instance to foo() from Kotlin,
// Java is a static call to foo()
class MyUtil {
companion object {
#JvmStatic fun foo() { ... }
}
}
And you would call it the same from Kotlin MyUtil.foo(). This is specifically the model of making a Kotlin method static.
Both examples look the same from Java in that they are just direct static calls to a static method. From Kotlin the first example is a static call as well, the second looks up an instance of the companion first and then does a virtual call on the method. The Second example creates two classes, the other only creates a single class.
The other options you present are not more efficient and are uglier syntax. Based on smallest byte code, fewest classes, and fastest performance pick the first example that is 1 class only and all static calls.

OO - Reduce boilerplate/forwarding code

Imagine the following: I have a bunch of DTO's that inherit from Foo class
class Foo { }
class FooA : Foo { }
class FooB : Foo { }
class FooX : Foo { }
Than I have one class that have encapsulated all the related logic and orchestration related with Foo data types. I provide a method DoSomethingWithData(Foo data) that do all the logic related to data provided by argument
The method implementation is something like this:
void DoSomething(Foo data)
{
if (data is FooA)
DoSomethingWithFooA((FooA) data);
if (data is FooB)
DoSomethingWithFooB((FooA)data);
if (data is FooX)
DoSomethingWithFooC((FooA)data);
}
This is a very simplified example. The advantage of this approach is:
The "Client" invoke always the DoSomething method independently of
the Foo data type
If I add a new type I only have to change the method DoSomething
What i dont like is the downcasting
The alternative is instead of exposing only DoSomething method I expose a method by each Foo data type. The advantage is that we dont have downcast but increases the boilerplate/forwarding code.
What do you prefer? Or do you have other approaches?
In this case, I would approach the problem like this (I will use Java for this example).
In your approach, for every subclass of Foo you have to provide a specific processing logic - as you have shown, and cast the Foo object to its sub-type. Moreover, for every new class that you add, you have to change the DoSomething(Foo f) method.
You can make the Foo class an interface:
public interface Foo{
public void doSomething();
}
Then have your classes implement this interface:
public class FooA iplements Foo {
public void doSomething(){
//Whatever FooA needs to do.
}
}
public class FooB implements Foo {
public void doSomething(){
//Whatever FooB needs to do.
}
}
And so on. Then, the client can call the doSomething() method:
...
Foo fooA = new FooA();
Foo fooB = new FooB();
fooA.doSomething();
fooB.doSomething();
...
This way, you don't have to cast the object at run-time and if you add more classes, you don't have to change your existing code, except the client that has to call the method of a newly added object.

Alternative to load method in Swift

I am working on developing an application in Swift. I wanted to design a system for the application that allowed for loose coupling between objects, and one strategy (which I have used successfully in other languages) was to create something I call an instance factory. It is pretty simple and here is the basic implementation I came up with in Swift:
import Foundation
private var typeGenerators = Dictionary<String, InstanceFactory.GeneratorCallback>()
public class InstanceFactory: NSObject {
public typealias GeneratorCallback = () -> AnyObject!
public class func registerGeneratorFor(typeName: String, callback: GeneratorCallback) {
typeGenerators[typeName] = callback
}
public class func instanceOf(typeName: String) -> AnyObject! {
return typeGenerators[typeName]?()
}
}
The idea is that when an object instance needs access to another object instance, rather than creating that instance outright which would more tightly couple the two objects, the first object would defer to the factory to provide the needed instance by calling the instanceOf method. The factory would know how to provide various instance types because those types would register with the factory and provide a closure that could generate the instance.
The trick is how to get the classes to register with the factory. I had previously made a similar factory in Objective-C and the way I got registration to work was to override the +load method for each class that needed to register with the factory. This worked great for Objective-C, and I figured it could work for Swift as well since I would be restricting the factory to only provide objects that are derived from NSObject. It appeared I got this to work and I spent a significant about of effort designing classes to make use of the factory.
However, after upgrading to Xcode 6.3, I discovered Apple has disallowed the usage of the load class method in Swift. Without this, I am unaware of a mechanism to allow classes to automatically register themselves with the factory.
I am wondering if there some other way to get the registration to work.
What alternatives are available that could allow classes to register with the factory, or what other techniques could be use to accomplish the same kind of loose coupling the factory provides?
I've found a possible solution to your problem after I wanted to register all ViewControllers that would be implementing a certain Protocol in my application and I ran into both this question and a possible answer.
The original was posted here: How to list all classes conforming to protocol in Swift?
I adapted it to Swift 3 and made it a bit more Swift-y and generic:
import UIKit
class ContextRoute: NSObject {
}
#objc protocol ContextRoutable {
static var route: ContextRoute { get }
}
class ContextRouter: NSObject {
private static var storedRoutes: [ContextRoute]?
static var routes: [ContextRoute] {
get {
if let storedRoutes = storedRoutes {
return storedRoutes
}
let routables: [ContextRoutable.Type] = classes(implementing: ContextRoutable.self)
let newRoutes = routables.map { routable in routable.route }
storedRoutes = newRoutes
return newRoutes
}
}
private class func classes<T>(implementing objcProtocol: Protocol) -> [T] {
let classes = classList().flatMap { objcClass in objcClass as? T }
return classes
}
private class func classList() -> [AnyObject] {
let expectedClassCount = objc_getClassList(nil, 0)
let allClasses = UnsafeMutablePointer<AnyClass?>.allocate(capacity: Int(expectedClassCount))
let autoreleasingAllClasses = AutoreleasingUnsafeMutablePointer<AnyClass?>(allClasses)
let actualClassCount:Int32 = objc_getClassList(autoreleasingAllClasses, expectedClassCount)
var classes = [AnyObject]()
for i in 0 ..< actualClassCount {
if let currentClass: AnyClass = allClasses[Int(i)],
class_conformsToProtocol(currentClass, ContextRoutable.self) {
classes.append(currentClass)
}
}
allClasses.deallocate(capacity: Int(expectedClassCount))
return classes
}
}
I tried it in my application and it works. I clocked it in the simulator and it takes 0.05s for an application that has about 12000 classes.
Consider taking the Swift approach using a protocol instead. I think the solution is actually simpler than the Objective-C approach. There are variations of this with Self constraints which are even better if you have more control over the classes.
// define a protocol to create an instance of a class
protocol FactoryInstantiable {
static func makeFactoryInstance() -> AnyObject
}
// Factory for generating new instances
public class InstanceFactory: NSObject {
public class func instanceOf(typeName: String) -> AnyObject! {
if let ProductType = NSClassFromString(typeName) as? FactoryInstantiable.Type {
return ProductType.makeFactoryInstance()
} else {
return nil
}
}
}
// your class which generally could be defined somewhere else
class MyClass {
var counter : Int
init(counter: Int) {
self.counter = 0
}
}
// extension of your class to conform to the FactoryInstantiable protocol
extension MyClass : FactoryInstantiable {
static func makeFactoryInstance() -> AnyObject {
return MyClass(counter: 0)
}
}

How do I mock an inherited method that has generics with JMockit

I have this abstract class:
public abstract class Accessor<T extends Id, U extends Value>
{
public U find(T id)
{
// let's say
return getHelper().find(id);
}
}
And an implementation:
public FooAccessor extends Accessor<FooId,Foo>
{
public Helper getHelper
{
// ...
return helper;
}
}
And I would like to mock the calls to FooAccessor.find.
This:
#MockClass(realClass=FooAccessor.class)
static class MockedFooAccessor
{
public Foo find (FooId id)
{
return new Foo("mocked!");
}
}
will fail with this error:
java.lang.IllegalArgumentException: Matching real methods not found for the following mocks of MockedFooAccessor:
Foo find (FooId)
and I understand why... but I don't see how else I could do it.
Note: yes, I could mock the getHelper method, and get what I want; but this is more a question to learn about JMockit and this particular case.
The only way around this I have found is to use fields
#Test
public void testMyFooMethodThatCallsFooFind(){
MyChildFooClass childFooClass = new ChildFooClass();
String expectedFooValue = "FakeFooValue";
new NonStrictExpectations(){{
setField(childFooClass, "fieldYouStoreYourFindResultIn", expectedFooValue);
}};
childFooClass.doSomethingThatCallsFind();
// if your method is protected or private you use Deencapsulation class
// instead of calling it directly like above
Deencapsulation.invoke(childFooClass, "nameOfFindMethod", argsIfNeededForFind);
// then to get it back out since you used a field you use Deencapsulation again to pull out the field
String actualFoo = Deencapsulation.getField(childFooClass, "nameOfFieldToRunAssertionsAgainst");
assertEquals(expectedFooValue ,actualFoo);
}
childFooClass doesn't need to be mocked nor do you need to mock the parent.
Without more knowledge of your specific case this strategy has been the best way for me to leverage jMockit Deencapsulation makes so many things possilbe to test without sacrificing visibility. I know this doesn't answer the direct question but I felt you should get something out of it. Feel free to downvote and chastise me community.
Honestly, I do not find it in any way different from mocking regular classes. One way to go is to tell JMockit to mock only the find method and use Expectations block to provide alternate implementation. Like this:
abstract class Base<T, U> {
public U find(T id) {
return null;
}
}
class Concrete extends Base<Integer, String> {
public String work() {
return find(1);
}
}
#RunWith(JMockit.class)
public class TestClass {
#Mocked(methods = "find")
private Concrete concrete;
#Test
public void doTest() {
new NonStrictExpectations() {{
concrete.find((Integer) withNotNull());
result = "Blah";
}}
assertEquals("Blah", concrete.work());
}
}
Hope it helps.

WCF Dependency injection and abstract factory

I have this wcf method
Profile GetProfileInfo(string profileType, string profileName)
and a business rule:
if profileType is "A" read from database.
if profileType is "B" read from xml file.
The question is: how to implement it using a dependency injection container?
Let's first assume that you have an IProfileRepository something like this:
public interface IProfileRepository
{
Profile GetProfile(string profileName);
}
as well as two implementations: DatabaseProfileRepository and XmlProfileRepository. The issue is that you would like to pick the correct one based on the value of profileType.
You can do this by introducing this Abstract Factory:
public interface IProfileRepositoryFactory
{
IProfileRepository Create(string profileType);
}
Assuming that the IProfileRepositoryFactory has been injected into the service implementation, you can now implement the GetProfileInfo method like this:
public Profile GetProfileInfo(string profileType, string profileName)
{
return this.factory.Create(profileType).GetProfile(profileName);
}
A concrete implementation of IProfileRepositoryFactory might look like this:
public class ProfileRepositoryFactory : IProfileRepositoryFactory
{
private readonly IProfileRepository aRepository;
private readonly IProfileRepository bRepository;
public ProfileRepositoryFactory(IProfileRepository aRepository,
IProfileRepository bRepository)
{
if(aRepository == null)
{
throw new ArgumentNullException("aRepository");
}
if(bRepository == null)
{
throw new ArgumentNullException("bRepository");
}
this.aRepository = aRepository;
this.bRepository = bRepository;
}
public IProfileRepository Create(string profileType)
{
if(profileType == "A")
{
return this.aRepository;
}
if(profileType == "B")
{
return this.bRepository;
}
// and so on...
}
}
Now you just need to get your DI Container of choice to wire it all up for you...
Great answer by Mark, However the solution given is not Abstract factory but the implementation of Standard Factory pattern. Please check how Marks classes fit in the Standard Factory Pattern UML diagram. Click here to see above classes applied to Factory pattern UML
Since in Factory pattern, the factory is aware of the concrete classes, we can make the code of the ProfileRepositoryFactory much simpler like below. The problem with injecting the different repositories to factory is that you have more code changes every time you add a new concrete type. With below code you only have to update the switch to include new concrete class
public class ProfileRepositoryFactory : IProfileRepositoryFactory
{
public IProfileRepository Create(string profileType)
{
switch(profileType)
{
case "A":
return new DatabaseProfileRepository();
case "B":
return new XmlProfileRepository();
}
}
}
Abstract Factory is more advanced pattern used for creating families of related or dependent objects without specifying their concrete classes. The UML class diagram available here explains it well.