android工場モード(二)

2043 ワード

ファクトリメソッドモード:オブジェクトを作成するインタフェースを定義しますが、サブクラスにどのインスタンスを作成するかを決定させます.ファクトリメソッドモードは、クラスのインスタンス化をサブクラスに遅延させます.ファクトリメソッドモードはクラスに属する作成型モードであり、マルチステートファクトリモードとも呼ばれる.
例:
//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