Learn Form Spring (1)-Command Pattern

I am reading a blog from http://www.iteye.com/problems/27338. And this paper enlightens me on the code refactoring subject and so on.
public static void main(String[] args) {
CreateBean bean = new CreateBean();
final String className = "com.test.AbstOO";
bean.create(className, new ObjectFactory() {
public Object getObject() {
try {
return Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
});

}
public class CreateBean {

public void create(String name, ObjectFactory factory) {
System.out.println("name=" + name);
Object obj = factory.getObject();
System.out.println("obj Name=" + obj.getClass().getName());
}
}

if dont use the callback, the usual code flow would be the Oject frist be created firstyl and then passed to the create method.
In that article, the writer says that this method use the Command Pattern. I am not sured about it. so I then look up the discription of Command pattern in the <Design Patterns in Java>. It writes "The ordinary way to cause a method to execute is to call it. there may be times, though, when u cant control the timing of or the context in which a method should execute. In these situations, you cam encapsulate a method inside an object. By storing the information necessary for invoking a method in an object, you can pass the method as a parameter, allowing the client or a service to determine when to invoke the method. In a word, The intent of the Command pattern is to encapsulate a request in an object."
From this reference, the CallBack is similar to the Command. Then look the orginal code in spring:
1.if (mergedBeanDefinition is Singleton) {   
sharedInstance = getSingleton(beanName, new ObjectFactory() {
public Object getObject() throws BeansException {
try {
return createBean(beanName, mergedBeanDefinition, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, mergedBeanDefinition);
}

A class can provide a hook - a way to insert custom code - by invoking a supplied command at a specific point in a procedure. The command pattern is similar to the Factory Method pattern in which a client konws when an action is requried but doesnot know exactly which operation to call.
A classic example of the usefulness of Command comes with menus. A menu item know when to execute an action but dont know which method to call. Command lets u parameterize a menu with the method calls that correspond to menu label.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值