In the previous post, i explained adapter, service and facade in the context of rest api. hier further design patterns in the spring boot/ Java context.
Six patterns, one REST-backed domain (City weather lookup), minimal code, minimal words.
1. Adapter
Translates an external contract into your domain model.
java
@Componentpublic class WeatherApiAdapter { private final RestClient restClient; public WeatherInfo fetch(String city) { ExternalWeatherDto dto = restClient.get() .uri("/weather?city={c}", city) .retrieve() .body(ExternalWeatherDto.class); return new WeatherInfo(dto.temp_c(), dto.condition().text()); }}
2. Repository
Abstracts persistence. Domain-oriented CRUD, no SQL leakage.
java
public interface CityRepository extends JpaRepository<City, Long> { Optional<City> findByName(String name);}
3. Service
Business logic. Orchestrates repositories/adapters, exposes use cases.
java
@Servicepublic class WeatherService { private final WeatherApiAdapter adapter; private final CityRepository cityRepository; public String forecastFor(String cityName) { City city = cityRepository.findByName(cityName) .orElseThrow(() -> new CityNotFoundException(cityName)); WeatherInfo info = adapter.fetch(city.getName()); return info.temp() > 25 ? "Hot in " + cityName : "Mild in " + cityName; }}
4. Proxy
Adds a cross-cutting concern (caching, auth, lazy-loading) transparently, same interface.
java
@Component@Primarypublic class CachingWeatherAdapter implements WeatherPort { private final WeatherApiAdapter delegate; private final Map<String, WeatherInfo> cache = new ConcurrentHashMap<>(); public WeatherInfo fetch(String city) { return cache.computeIfAbsent(city, delegate::fetch); }}
5. Facade
One simplified entry point over several subsystems.
java
@Componentpublic class TripPlannerFacade { private final WeatherService weatherService; private final FlightService flightService; private final HotelService hotelService; public TripPlan planTrip(String city) { return new TripPlan( weatherService.forecastFor(city), flightService.findFlights(city), hotelService.findHotels(city)); }}

Hinterlasse einen Kommentar