Design Patterns in Action Script-Template Method

Do you like playing cards? If your had ever played, you may noticed that everyone has their own way arranging the cards. And in most cases, people will put the cards in order, maybe from the biggest one to the smallest one. Eh, this is a way of sorting.

We can write down the following code to mimic this action.

 

  1. public function sort ( array : Array ) : void
  2. {
  3.     for ( var   i : int = 0 ; i < array . length ; i ++ )
  4.     {
  5.         for ( var   j : int = 0 ; j < array . length - i ; j ++ )
  6.         if (   ( int )( array [ j ]) < ( int )( array [ j + 1 ]) )
  7.             swap ( array , j , j + 1 ) ;
  8.     }
  9. }

Here, I use the bubble sort, not insertion sort. Because I think the bubble sort is easy to understand. Using this sort will make you cards arrange from the biggest to the smallest, and the sequence is from left to right. Eh, maybe you don’t like to this sequence, you’d like to hold the cards from the smallest to the biggest, and also it’s from left to right.

Of course, you can change the code with your sorting logic. But, you’ll find that you just need to change the compare logic. Maybe, we can extract the compare logic to another function. And the code will be as follows.

  1. for ( var i : int = 0 ; i < array . length ; i ++ )
  2. {
  3.     for ( var   j : int = 0 ; j < array . length - i ; j ++ )
  4.     if (   compare ( array , j , j + 1 ) )
  5.         swap ( array , j , j + 1 ) ;
  6. }

Now, we can rewrite the compare function to get a different result. Let’s go further, we don’t need to implement the compare method now, we can delay it to the subclass. Then, each subclass can get its own way of sorting by override the compare function.

And the class diagram will be.

clip_image001

Aha, a new pattern! And it’s called template method.

The intent is here.

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

– By THE GOF BOOK

As you see the skeleton of our sorting algorithm is defined in the template class, and the compare function is use for the subclass to redefine.

This pattern is very useful especially when your high level design is stable, but the detail needs to change frequency.

Search-256x256Demo | DownloadDownload Full Project

Enjoy!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值