Design Runtime Data Source Access Layer
Design a data access layer that can retrieve and update data while allowing its underlying data source to change at runtime.
The supported data sources are "DATABASE", "API", and "FILE". The business logic must remain independent of the selected data source.
Use Strategy pattern to separate data access behavior from business logic. Use a Factory to create the appropriate data source implementation.
Class Definition
DataAccessService(String initialDataSource)
initialDataSource specifies the data source used when the service is created.
- Each supported data source maintains its own independent collection of key-value records.
- Every data source starts with an empty collection.
Method Signatures
String retrieveData(String key)
- Retrieves the value associated with
key from the currently selected data source.
- Returns an empty string if the key does not exist.
boolean updateData(String key, String value)
- Adds or replaces the value associated with
key in the currently selected data source.
- Returns
true after the record is successfully stored.
boolean changeDataSource(String dataSourceType)
- Changes the data source used by subsequent retrieval and update operations.
- Returns
true when dataSourceType is supported.
- Returns
false and keeps the current data source unchanged when the requested type is unsupported.
Deterministic Behavior
- Supported source names are matched exactly and are case-sensitive.
- The supported values are
"DATABASE", "API", and "FILE".
- Updating an existing key replaces its previous value.
- An unsuccessful source change does not modify the active source.
Constraints
initialDataSource is one of "DATABASE", "API", or "FILE".
1 ≤ key.length() ≤ 100
0 ≤ value.length() ≤ 10,000
- At most
100,000 method calls are made on one service instance.
- No parameter passed to the constructor or any method is
null.
Example 1
DataAccessService(initialDataSource = "DATABASE")
updateData(key = "theme", value = "dark") returns true.
retrieveData(key = "theme") returns "dark".
changeDataSource(dataSourceType = "FILE") returns true.
retrieveData(key = "theme") returns "" because the file data source has its own records.
Example 2
DataAccessService(initialDataSource = "API")
updateData(key = "status", value = "active") returns true.
changeDataSource(dataSourceType = "DATABASE") returns true.
updateData(key = "status", value = "pending") returns true.
changeDataSource(dataSourceType = "API") returns true.
retrieveData(key = "status") returns "active".
Example 3
DataAccessService(initialDataSource = "FILE")
updateData(key = "version", value = "1") returns true.
changeDataSource(dataSourceType = "CACHE") returns false.
retrieveData(key = "version") returns "1" because "FILE" remains the active data source.