工作中的几种设计模式

来源:互联网 发布:小型网络机柜 编辑:程序博客网 时间:2024/06/06 11:35

1.单例模式

synchronized public static ImCache getInstance   (Context context) {      if (sInstance == null) {          sInstance = new ImCache(context);      }      return sInstance;  }  
优点
  • 由于单例模式在内存中只有一个实例,减少了内存开支,特别是一个对象需要频繁地创建、销毁时,而且创建或销毁时性能又无法优化,单例模式的优势就非常明显。
  • 由于单例模式只生成一个实例,所以减少了系统的性能开销,当一个对象的产生需要比较多的资源时,如读取配置、产生其他依赖对象时,则可以通过在应用启动时直接产生一个单例对象,然后用永久驻留内存的方式来解决;
  • 单例模式可以避免对资源的多重占用,例如一个写文件动作,由于只有一个实例存在内存中,避免对同一个资源文件的同时写操作。
  • 单例模式可以在系统设置全局的访问点,优化和共享资源访问,例如可以设计一个单例类,负责所有数据表的映射处理。
缺点
  • 单例模式一般没有接口,扩展很困难,若要扩展,除了修改代码基本上没有第二种途径可以实现。

2.builder模式

    ImSession session = sb.looper(mImModule.getLooper())            .listener(mImModule)            .config(mImModule.getImConfig())            .imsService((IImServiceInterface)HandlerFactory.getStackAdaptor(IImServiceInterface.class))            .slmService((ISlmServiceInterface)HandlerFactory.getStackAdaptor(ISlmServiceInterface.class))            .uriGenerator(mImModule.getUriGenerator())            .mnoStrategy(mImModule.getMnoSpecificStrategy())            .chatId(StringIdGenerator.generateChatId(participants, participants.size() > 1))            .participantsUri(participants)            .ownPhoneNum(mImModule.getOwnPhoneNum())            .subject(event.mWelcomeNote)            .contributionId(event.mContributionId)            .conversationId(event.mConversationId)            .sdpContentType(event.mSdpContentType)            .direction(ImDirection.INCOMING)            .rawHandle(event.mIsDeferred ? null : event.mRawHandle)            .capability(mImModule.getChatSessionCapability())            .sessionType(event.mSessionType)            .build();
  • 良好的封装性, 使用建造者模式可以使客户端不必知道产品内部组成的细节;
  • 建造者独立,容易扩展;
  • 在对象创建过程中会使用到系统中的一些其它对象,这些对象在产品对象的创建过程中不易得到。

3.adapter模式

public interface IDataAdapter {/** * this method will adapt the xml element to profileData * * @param element the input xml element * @return the output profileData */public ProfileData buildProfileData(Element element);/** * this method will adapt the profileData to xml element * * @param profileData the input profileData * @param document the input W3G document, which will used to make element * @return the output xml element */public Element buildXmlElement(ProfileData profileData, Document document);/** * compare the two ContentValues and return the compare result * <p> * this method is used to compare two profileInfo, * * @param valuesA the input ContentValues to be compared * @param valuesB the input ContentValues to be compared * @return the compare result: {@link CompareResult} */public int compare(ContentValues valuesA, ContentValues valuesB);public String getMimeType();public String getTagName();public String getElementType();public interface CompareResult {    public final static int SAME = 0;    public final static int SHOULD_UPADATE = 1;    public final static int NOT_RELATED = -1;}}
优点
  • 更好的复用性
      系统需要使用现有的类,而此类的接口不符合系统的需要。那么通过适配器模式就可以让这些功能得到更好的复用。

  • 更好的扩展性
      在实现适配器功能的时候,可以调用自己开发的功能,从而自然地扩展系统的功能。

缺点
  • 过多的使用适配器,会让系统非常零乱,不易整体进行把握。比如,明明看到调用的是A接口,其实内部被适配成了B接口的实现,一个系统如果太多出现这种情况,无异于一场灾难。因此如果不是很有必要,可以不使用适配器,而是直接对系统进行重构。

4.观察者模式

    mPersister = new ImPersister(mContext, mImModule);    addObserver(mPersister);    chatData.triggerObservers(ImCacheAction.INSERTED);    public void update(Observable observable, Object data) {        ChatData chatData = (ChatData) observable;        ImCacheAction action = (ImCacheAction) data;        if (action == ImCacheAction.INSERTED) {            insertSession(chatData);        } else if (action == ImCacheAction.UPDATED) {            onSessionUpdated(chatData);        } else if (action == ImCacheAction.DELETED) {            deleteSession(chatData);        }    }
优点

观察者和被观察者之间是抽象耦合

5.策略模式

private static IMnoStrategy createMnoStrategy(Context ctx) {        String mcc = getMccFromConfiguration();        String mnc = getMncFromConfigurtion();        Mno mno = new Mno(Mcc.parseMcc(mcc), Mnc.parseMnc(mnc));        Log.d(LOG_TAG, "createMnoStrategy " + mno);        if (sMnoSpecificStrategyGenerator.containsKey(mno)) {            Class<?> cls = sMnoSpecificStrategyGenerator.get(mno);            return (IMnoStrategy) cls.getConstructor(Context.class).newInstance(ctx);        }

策略模式主要用来分离算法,根据相同的行为抽象来做不同的具体策略实现。
通过以上也可以看出策略模式的优缺点:

优点:
  • 耦合度相对而言较低,扩展方便。
  • 操作封装也更为彻底,数据更为安全。
缺点:
  • 随着策略的增加,子类也会变得繁多。

6.proxy模式

 ICapabilityServiceEventListener.Stub mEventProxy = new             ICapabilityServiceEventListener.Stub() {       @Override       public void onOwnCapabilitiesChanged() throws RemoteException   {          if (mRelay == null) {              Log.d(LOG_TAG, "no listener for ICapabilityServiceEventListener");              throw new RemoteException();          } else {              mRelay.onOwnCapabilitiesChanged();          }      }  

给对象增加了本地化的扩展性,增加了存取操作控制

7.组合模式

ServiceModuleManager总体管理各个Module

优点
  • 不破坏封装,整体类与局部类之间松耦合,彼此相对独立 。
  • 具有较好的可扩展性。
  • 支持动态组合。在运行时,整体对象可以选择不同类型的局部对象。
    整体类可以对局部类进行包装,封装局部类的接口,提供新的接口。
缺点
  • 整体类不能自动获得和局部类同样的接口。
  • 创建整体类的对象时,需要创建所有局部类的对象 。

8.装饰模式

output = new BufferedOutputStream(new FileOutputStream (mRequest.mFilePath, mTransferred > 0), bufferSize);
优点
  1. 可以通过一种动态的方式来扩展一个对象的功能,在运行时选择不同的装饰器,从而实现不同的行为。
  2. 通过使用不同的具体装饰类以及这些装饰类的排列组合,可以创造出很多不同行为的组合。可以使用多个具体装饰类来装饰同一对象,得到功能更为强大的对象。
  3. 具体构件类与具体装饰类可以独立变化,用户可以根据需要增加新的具体构件类和具体装饰类,在使用时再对其进行组合,原有代码无须改变,符合“开闭原则”。

9.状态模式

EVENT_SEND_MESSAGE   -->InitialState          MessageBase imMsg = (MessageBase) msg.obj;          onStartSession(imMsg, mIsRejoinable);   -->EstablishedState          onSendImMessage((MessageBase) msg.obj);   -->ClosingState          ....

它将与特定状态相关的行为局部化,并且将不同状态的行为分割开来

0 0
原创粉丝点击