工厂方法模式:定义一个用于创建对象的接口,但是让子类来决定到底创建哪一个实例。工厂方法模式让一个类的实例化延迟到其子类。工厂方法模式同样属于类的创建型模式又被称为多态工厂模式
实例:
//Abstract product roles
interface Events{
public void decEvents();
}
//Click on the event,The specific role
class ClickEvents implements Events{
public void decEvents(){
LogHelper.w("This event is a click event");
}
}
//Search on the event,The specific role
interface SearchEvents{
public void decEvents(){
LogHelper.w("This event is a search event");
}
}
//Login on the event,The specific role
interface LoginEvents{
public void decEvents(){
LogHelper.w("This event is a login event");
}
}
//Abstract factory role
public interface EventsFactory{
public Events createEvents();
}
//Click on the factory interface
public interface ClickEventsFactory implements EventsFactory {
@Override
public Events createEvents(){
Events events = new ClickEvents();
return events;
}
}
//Search on the factory interface
public interface SearchEventsFactory implements EventsFactory {
@Override
public Events createEvents(){
Events events = new SearchEvents();
return events;
}
}
//Login on the factory interface
public interface LoginEventsFactory implements EventsFactory {
@Override
public Events createEvents(){
Events events = new LoginEvents();
return events;
}
}
在MainActivity点击事件中实例化,并使用:
EventsFactroy factory;
Events events;
//Click product
factory = new ClickEventsFactory();
events = factory.createEvents();
events.decEvents();
//search product
factory = new SearchEventsFactory();
events = factory.createEvents();
events.decEvents();
//Login product
factory = new LoginEventsFactory();
events = factory.createEvents();
events.decEvents();
显示结果:
This event is a click event
This event is a search event
This event is a login event