Decorators (Wrappers)

Another common from of delegation is the decorator or wrapper. Decorators are a design pattern that adds a behavior to a class without the using inhertiance. The decorator does this by implementing the interface of an object and wrapping a copy of that object inside itself. Java InputStream class is an example of this pattern used in the wild. Decorators are used to a buffering and various other capablities to it.

decoratorUML

class ZeroElementListDecorator(val arrayAdapter: ListAdapter) : 
    ListAdapter by arrayAdapter { 
  override fun getCount(): Int = arrayAdapter.count + 1 
  override fun getItem(position: Int): Any? = when { 
      position == 0 -> null 
      else -> arrayAdapter.getItem(position - 1) 
  } 

  override fun getView(position: Int, convertView: View?,parent: 
ViewGroup): View = when { 
    position == 0 -> parent.context.inflator
        .inflate(R.layout.null_element_layout, parent, false) 
    else -> arrayAdapter.getView(position - 1, convertView, parent) 
  } 
} 

override fun getItemId(position: Int): Long = when { 
  position == 0 -> 0 
  else -> arrayAdapter.getItemId(position - 1) 
}

to use

val arrayList = findViewById(R.id.list) as ListView 
    val list = listOf("A", "B", "C") 
    val arrayAdapter = ArrayAdapter(this, 
          android.R.layout.simple_list_item_1, list) 
    arrayList.adapter = ZeroElementListDecorator(arrayAdapter)

results matching ""

    No results matching ""