您的位置:首页 > 其它

门面模式

2013-10-09 23:57 381 查看

设计模式——门面模式

一、引言

  很多时候我们只是知道一个物品,至于它是怎么产生的,我们不得而之。比如邮局里面是怎么操作信件的,我们只是需要将写的情信拿到邮箱就可以了,并不用理会它将通过怎么一个形式,或者怎么的途径将我表达的爱传播出去的。这也导致了之前我们很乐意的花钱买三聚氰胺奶粉来喝。

二、门面模式

  1. 定义:门面模式了叫外观模式,它提供一个高层次的接口,使得子系统更易于使用,门面模式注重“统一对象”,也就是提供一个访问子系统的接口,除了这个接口不允许有任何访问子系统的行为发生。

  2. 示意图:【如下图所示】



  3. 示意图说明:门面模式,是提供给客户调用的一个途径,使得客户端不必与底层的子系统进行交互。屏蔽高层对低层的直接访问。如图,当我们在Spring里取Bean的时候,只需要调用ServiceFacade就行了,而无须直接接触相应的Bean。

三、门面模式示例

  1. Service

package com.swyma.spring.service;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
* 登录 Service
* @author yemaoan
*
*/
@Service
@Scope("prototype")
public class LoginService extends BasicService {

public void check(String username, String password) {

}

public void handle() {
System.out.println("login handle");
}
}


package com.swyma.spring.service;

import org.springframework.stereotype.Service;

/**
* 注册 Service
* @author yemaoan
*
*/
@Service
public class RegisterService extends BasicService {

public void create() {

}

}


package com.swyma.spring.service;

import org.springframework.stereotype.Service;

import com.swyma.spring.entity.User;

/**
* 用户 Service
* @author yemaoan
*
*/
@Service
public class UserService extends BasicService {

public void create(User user) {

}

public void modify(User user) {

}

public void delete(User user) {

}

}


  2. ServiceFacade

package com.swyma.spring.service;

import com.swyma.spring.core.ISpringContext;

/**
* Service门面
* @author yemaoan
*
*/
public class ServiceFacade {

/**
* 取Spring上下文
* @return
*/
public static ISpringContext getContext() {
ISpringContext context = new BasicSpringContext();
return context;
}

public static LoginService getLoginService() {
return getContext().lookup(LoginService.class);
}

public static UserService getUserService() {
return getContext().lookup(UserService.class);
}

public static RegisterService getRegisterService() {
return getContext().lookup(RegisterService.class);
}

}


  3. Client

package com.swyma.spring.test;

import org.junit.Test;

import com.swyma.spring.core.ISpringContext;
import com.swyma.spring.entity.User;
import com.swyma.spring.service.BasicSpringContext;
import com.swyma.spring.service.LoginService;
import com.swyma.spring.service.RegisterService;
import com.swyma.spring.service.ServiceFacade;
import com.swyma.spring.service.UserService;

/**
* JUintTest
* @author yemaoan
*
*/
public class TestSpringEnv {

@Test
public void testFacade() {
ServiceFacade serviceFacade = new ServiceFacade();
LoginService loginService = serviceFacade.getLoginService();
loginService.handle();
}

}


四、总结

  1. 门面是一个很好的封装方法,用于向客户端提供一个访问子系统的途径。

  2. 门面模式不参与子系统内的业务逻辑,即是它不能控制子系统的里规定的流程。

  3. 门面对象知晓子系统的全部功能和责任,它是一个没有实际业务逻辑的委托类。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: