java - Is there any elegant way to handle calls from different sources differently for the same method?
淡淡烟草味
淡淡烟草味 2017-07-03 11:42:06
0
2
1177

When I was writing a control.
There is a classsubViewPagerthat inheritsViewPager. I need to use thegetCurrentItem()method of thisViewPagerin another place. , which means to obtain a certain coordinate of this control.

But because myViewPageris for special effects, the coordinates returned by itsgetCurrentItem()may exceed the length of my data collectionsize,

For example, the length of my data collection issize = 1024
andgetCurrentItem()returns40280

So when I call him actively, I hope that he can return to me the result of coordinates%=size: 4028 24.

At the same time, hisgetCurrentItem()method should return a number like40280when called by the system.

My original approach was to write a special method to obtain the result after%=size. Force it when you need to get this parameter.

Later I changed a bit and usednew Exception().getStackTrace();to obtain the call stack information to determine whether the method was called by the specified class. This eliminates the need to force and write a subclass-specific method.

But this approach will generate a lot of garbage memory and frequently causeGC, so consider using the first method to deal with it.
But forced transfer is always a bit unpleasant, and it feels like there is no reusability. (Although it is because of the bad code... and the reusability ofsubViewPageris also reduced by doing this) So I want to ask if there is any way to make the same method be called in different classes. Can you perform different operations gracefully?

淡淡烟草味
淡淡烟草味

reply all (2)
大家讲道理

Isn’t it enough for subViewPager to override getCurrentItem()? .

    学霸

    I have seen implementation solutions of similar libraries. If the business logic returned by your internal and external calls of this method is not consistent, it is recommended to define an additional method...such asgetCurrentRealItem()

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!