Author - StudySection Post Views - 714 views
Salesforce Apex

Decorator Pattern in Salesforce Apex

A decorator pattern in Salesforce Apex allows the user to add new functionality to an existing object without changing the subject’s structure. This design pattern is a type of structural pattern as this pattern acts as a wrapper to the existing class.
This pattern is used to create a decorator class that wraps the original class and provides additional functionality keeping the class methods signature intact.

Need: You may want to use the decorator pattern because of the following reasons-

  • Sometimes developers want to use a selection checkbox whose value they don’t want to be stored in the database.
  • Sometimes developers want to use a complex calculated field to be displayed on the page, which is impossible through formula.
  • Sometimes developers want to use a proxy field, which is converted to a different value on the record when updated.

Problem:
As a user, I want to perform some operations on selected records using the VF page
Solution:
We solve it using the decorator pattern which extends the subject functionality. Let’s solve it with an example.
Apex Class:
public with sharing class DecoratorExample {
public List<DecoratorWrapper> accounts {get; set;}
public DecoratorExample() {
accounts = new List<DecoratorWrapper>();
for(Account eachRecord : [SELECT Id, Name FROM Account]){
accounts.add(new DecoratorWrapper(false, eachRecord));
}
}
public void performOperation(){
//perform operation
}
public class DecoratorWrapper{
public Boolean checkBoxValue{get; set;}
public Account record{get; set;}
public DecoratorWrapper(Boolean checkBoxValue, Account record){
this.checkBoxValue = checkBoxValue;
this.record = record;
}
}
}

VF Page:
<apex:page controller="DecoratorExample ">
<apex:pageBlock>
<apex:pageBlockButtons>
<apex:commandButton action="{!performOperation}" value="Perform Operation"/>
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!accounts}" var="eachRecord">
<apex:column value="{!eachRecord.checkBoxValue}" headerValue = "Check box"/>
<apex:column value="{!eachRecord.record.Id}" headerValue = "Id"/>
<apex:column value="{!eachRecord.record.Name}" headerValue = "Name"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

The English language is the most widely used language as a medium of communication around the world. Having a certification for the English language can be an advantage. StudySection provides an English Certification Exam that tests English language proficiency in English grammar, reading, and writing.

Leave a Reply

Your email address will not be published. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri