1

There is an existing functionality with below pseudo code

class MyMessageSink implements MessageSink {
        public void sendToFulfillment();
}

Now, I would like to add transaction & locking capability to the sendToFulfillment method. I did this using wrapper pattern

class TransactionalMessageSink{
      private MessageSink sink;
      public TransactionalMessageSink(MessageSink sink){
                this.sink = sink;
          }
       public void sendToFulfillment(){
            //start transaction
            sink.sendToFulfillment();
            //end transaction     
        }
}

Similarly, I created a LockingMessageSink and the client code became

new LockingMessageSink(new TransactionalMessageSink(new MyMessageSink())).sendToFulfillment

However, the transaction & locking code is very less, simple and straightforward (since we are using a framework which does most of the boilerplate work for us). So I though of another approach -

class MyMessageSink implements MessageSink {
            public void lockAndSendToFulfillmentInTransaction(){
                    //locking start
                     sendToFulfillmentInTransaction();
                    //locking end
            }

            public void  sendToFulfillmentInTransaction(){ 
                     //transaction start
                      sendToFulfillment();
                     //transaction end
            }
            public void sendToFulfillment();
    }

The problem here is obvious, there is a tight coupling between the locking and transaction code but avoids creation of 2 additional classes for simple functionality.

I personally like the first approach, but still am not convinced that this is the best one.

My question - Is there a better way other than using Wrapper, i.e any efficient way to handle these in a single class without compromising on the design aspect.

4

1 回答 1

0

Sounds like you need Aspect Oriented Programming. If you are using Java, take a look at AspectJ

Transactions and other "aspects" such as logging are known as cross-cutting concerns that need to be implemented in multiple designs and abstractions. AOP can be used to automatically wrap your methods with boilerplate to do transactions or logging etc.

于 2013-10-11T22:27:34.727 回答