Spring中的常用设计模式及使用示例
单例模式(Singleton Pattern)
控制一个类只能有一个对象实例,并提供全局访问点。在Spring框架中,Bean默认为单例模式,可以通过在配置文件中指定scope属性为"prototype"来修改Bean的作用域。
@Scope("singleton")
@Component
public class SingletonClass {
// ...
}
bean,因为它们是单例,必须是thread safe的。一个class,这个class存储着一个reference指向自己,或者说,一个自己的instance。然后,有一个private constructor,然后有一个static getinstance method 去返回自己, 把constructor私有化使得你在getInstance method用不了new method去构建新的instance。由于多线程同时共享同一个instance,那么你在调用时必须引入一些locking的logic,比如synchronized block去保证unsafe的情况。
工厂模式(Factory Pattern)
工厂类用于创建其他对象,工厂模式就是让工厂去建造相似但不同类型的classes。这些对象是共享同一个interface或者来自于同一个parent class的。
@Component
public class Factory {
@Autowired
private ProductA productA;
public ProductA createProductA() {
return productA;
}
}
工厂模式贯穿于整个Spring的设计当中。其中一个用得最多的地方就是BeanFactory,除了BeanFactory,Spring还有FactoryBean,这个是工厂的工厂。IoC容器是基于Application context的,而Application context是扩展 Beanfactory的,是Beanfactory的一个wrapper。Application context就是所有Object存储的供应工厂。
开发一个adoptPet API给用户去领养一个宠物,用户会传入他想要宠物类型(假定目前我们能提供的有小猫(cat)和小狗(dog)两种类型),并且用户会传入他想给的名字。
1、构建interface
public interface Pet {
void setName(String name);
String getName();
String getType();
Boolean isHungry();
void feed();
}
2、创建两个类给小猫和小狗
public class Cat implements Pet {
//save some code here
}
public class Dog implements Pet {
//save some code here
}
3、创建工厂class,注意,工厂返回的object是Pet interface,不是具体小猫小狗对象。
public class PetFactory {
public Pet createPet(String animalType){
switch(animalType.toLowerCase()){
case "dog":
return new Dog();
case "cat":
return new Cat();
default:
throw new UnsupportedOperationException("unknown animal type");
}
}
}
4、调用工厂模式创建实例
@PostMapping("adopt/{type}/{name}")
public Pet adoptPet(@PathVariable String type, @PathVariable String name){
Pet pet = this.petFactory.createPet(type);
pet.setName(name);
pet.feed();
return pet;
}
抽象工厂模式(Abstract Factory Pattern)
public interface AbstractFactory {
ProductA createProductA();
ProductB createProductB();
}
@Component
public class Factory implements AbstractFactory{
@Autowired
private ProductA productA;
@Autowired
private ProductB productB;
public ProductA createProductA() {
return productA;
}
public ProductB createProductB() {
return productB;
}
}
建造者模式(Builder Pattern)
为了取代去一个对象的参数的反复setter。
builder pattern的实现核心在于每个method都返回builder object 本身。然后连起来给builder object赋值,最后利用build method返回需要使用的object。
@Component
public class ProductBuilder {
private String property1;
private String property2;
private String property3;
public ProductBuilder setProperty1(String property1) {
this.property1 = property1;
return this;
}
public ProductBuilder setProperty2(String property2) {
this.property2 = property2;
return this;
}
public ProductBuilder setProperty3(String property3) {
this.property3 = property3;
return this;
}
public Product build() {
return new Product(property1, property2, property3);
}
}
// 使用时
Product product = new ProductBuilder().setProperty1("123")
.setProperty2("abc").setProperty3("name").build();
原型模式(Prototype Pattern)
@Component
@Scope("prototype")
public class PrototypeClass implements Cloneable {
// ...
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
实践参考:Java高效编程之Builder模式
适配器模式(Adapter Pattern)
@Component
public class Adapter implements Target {
@Autowired
private Adaptee adaptee;
@Override
public void request() {
adaptee.specialRequest();
}
}
桥接模式(Bridge Pattern)
public abstract class Abstraction {
@Autowired
protected Implementor implementor;
public void operation() {
implementor.operationImp();
}
}
@Component
public class RefinedAbstraction extends Abstraction {
// ...
}
public interface Implementor {
void operationImp();
}
@Component
public class ConcreteImplementor implements Implementor {
// ...
}
装饰器模式(Decorator Pattern)
装饰器模式让对原始对象的创建,变为对装饰对象的创建和使用。
public interface MyService {
void doSomething();
}
public class MyServiceImpl implements MyService {
@Override
public void doSomething() {
System.out.println("Do something in MyServiceImpl.");
}
}
public class MyServiceDecorator implements MyService {
private MyService target;
public MyServiceDecorator(MyService target) {
this.target = target;
}
@Override
public void doSomething() {
System.out.println("Before doSomething.");
target.doSomething();
System.out.println("After doSomething.");
}
}
// 使用示例
MyService myService = new MyServiceDecorator(new MyServiceImpl());
myService.doSomething();
在Spring中,装饰器模式的实现方式是使用AOP的前置/后置通知。例如:
@Component
@Aspect
public class MyServiceAspect {
@Before("execution(* com.example.MyService.doSomething())")
public void beforeDoSomething() {
System.out.println("Before doSomething.");
}
@After("execution(* com.example.MyService.doSomething())")
public void afterDoSomething() {
System.out.println("After doSomething.");
}
}
@Service
public class MyServiceImpl implements MyService {
@Override
public void doSomething() {
System.out.println("Do something in MyServiceImpl.");
}
}
// 在Spring配置文件中配置
<aop:aspectj-autoproxy />
<bean class="com.example.MyServiceAspect" />
<bean id="myService" class="com.example.MyServiceImpl" />
外观模式(Facade Pattern)
@Component
public class Facade {
@Autowired
private Subsystem1 subsystem1;
@Autowired
private Subsystem2 subsystem2;
@Autowired
private Subsystem3 subsystem3;
public void operation() {
subsystem1.operation1();
subsystem2.operation2();
subsystem3.operation3();
}
}
享元模式(Flyweight Pattern)
@Component
public class FlyweightFactory {
private Map<String, Flyweight> flyweights = new HashMap<>();
public Flyweight getFlyweight(String key) {
if (flyweights.containsKey(key)) {
return flyweights.get(key);
} else {
Flyweight flyweight = new ConcreteFlyweight(key);
flyweights.put(key, flyweight);
return flyweight;
}
}
}
代理模式(Proxy Pattern)
在Spring中代理模式的使用在很多地方都体现,比如创建Bean对象时、AOP切面实现时等等。
创建基本接口:
public interface Subject {
void operation();
}
创建被代理类:
@Component
public class RealSubject implements Subject {
@Override
public void operation() {
System.out.println("I am a real subject");
}
}
创建代理类:
@Component
public class Proxy {
@Autowired
private RealSubject realSubject;
public void operation() {
System.out.println("proxy for a real subject");
realSubject.operation();
}
}
观察者模式(Observer Pattern)
建立观察者,当变化出现时,通知观察者。
public interface MyObserver {
void update(MyObservable observable);
}
public class MyObservable {
private ArrayList<MyObserver> observers = new ArrayList<>();
public void addObserver(MyObserver observer) {
observers.add(observer);
}
public void removeObserver(MyObserver observer) {
observers.remove(observer);
}
public void notifyObservers() {
for (MyObserver observer : observers) {
observer.update(this);
}
}
public void doSomething() {
System.out.println("Do something in MyObservable.");
notifyObservers();
}
}
public class MyObserverImpl implements MyObserver {
@Override
public void update(MyObservable observable) {
System.out.println("Update in MyObserverImpl.");
}
}
// 使用示例
MyObservable myObservable = new MyObservable();
MyObserver myObserver = new MyObserverImpl();
myObservable.addObserver(myObserver);
myObservable.doSomething(); // 输出:Do something in MyObservable. Update in MyObserverImpl.
在Spring中,观察者模式的实现方式是使用事件机制。
@Component
public class MyEventPublisher {
@Autowired
private ApplicationEventPublisher eventPublisher;
public void publishEvent() {
eventPublisher.publishEvent(new MyEvent(this));
}
}
public class MyEvent extends ApplicationEvent {
public MyEvent(Object source) {
super(source);
}
}
@Component
public class MyEventHandler implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent event) {
System.out.println("Handle MyEvent.");
}
}
// 在Spring配置文件中配置
<bean class="com.example.MyEventPublisher" />
<bean class="com.example.MyEventHandler" />