Salesforce 架构篇总结(三)Service 层的一些原则

主要目标

创建一个 Service 层的 class 并且在应用中高效的使用
暴露出一个用 Service 层做的 API

创建 Service

下面介绍的这个方法展示了使用 service 利用 discount 来建立一组 discount

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public with sharing class OpportunitiesService
{
public static void applyDiscounts(Set<Id> opportunityIds, Decimal discountPercentage)
{
// Validate parameters
if(opportunityIds == null || opportunityIds.size() == 0)
{
throw new OpportunityServiceException('Opportunities not specified.');
}

if(discountPercentage < 0 || discountPercentage > 100)
{
throw new OpportunityServiceException('Invalid discount to apply.');
}

// Query Opportunities and Lines (SOQL inlined for this example, see Selector pattern in later module)
List<Opportunity> opportunities =[select Amount, (select UnitPrice from OpportunityLineItems)
from Opportunity where Id in :opportunityIds];

// Update Opportunities and Lines (if present)
List<Opportunity> oppsToUpdate = new List<Opportunity>();
List<OpportunityLineItem> oppLinesToUpdate = new List<OpportunityLineItem>();

Decimal factor = 1 - (discountPercentage == null ? 0 : discountPercentage / 100);

for(Opportunity opportunity : opportunities)
{
// Apply to Opportunity Amount
if(opportunity.OpportunityLineItems != null && opportunity.OpportunityLineItems.size() > 0)
{
for(OpportunityLineItem oppLineItem : opportunity.OpportunityLineItems)
{
oppLineItem.UnitPrice = oppLineItem.UnitPrice * factor;
oppLinesToUpdate.add(oppLineItem);
}
}
else
{
opportunity.Amount = opportunity.Amount * factor;
oppsToUpdate.add(opportunity);
}
}

// Update the database
SavePoint sp = Database.setSavePoint();

try
{
update oppLinesToUpdate;
update oppsToUpdate;
}
catch (Exception e)
{
// Rollback
Database.rollback(sp);
// Throw exception on to caller
throw e;
}
}

public class OpportunityServiceException extends Exception {}
}

评论