Kurs JavaScript i React · Moduł 8: Zaawansowane wzorce React

Wzorzec Adapter i Facade

7 min czytania ·
W tej lekcji4

W kosmicznej podróży przez React, nasz statek musi łączyć się z wieloma różnymi systemami - stacjami kosmicznymi, satelitami, bazami na planetach. Każdy z tych systemów ma swój własny protokół komunikacji. Wzorce Adapter i Facade to jak uniwersalny translator, który pozwala naszemu statkowi porozumieć się z dowolnym systemem bez konieczności znajomości jego wewnętrznych szczegółów.

Wzorzec Adapter

Czym jest Adapter?

Wzorzec Adapter (znany też jako Wrapper) pozwala na współpracę obiektów o niekompatybilnych interfejsach. W React używamy go najczęściej do opakowywania zewnętrznych API spójnym, przewidywalnym interfejsem.

Wyobraź sobie, że Twoja kosmiczna baza danych pogodowych na różnych planetach korzysta z trzech różnych dostawców API. Każdy z nich zwraca dane w innym formacie. Adapter pozwala ujednolicić te dane:

// Surowe odpowiedzi z różnych API kosmicznych
// API Marsa zwraca: { temp_celsius: -60, wind_kph: 25, condition: "dusty" }
// API Jowisza zwraca: { temperature: { value: -145, unit: "C" }, windSpeed: 350 }
// API Saturna zwraca: { readings: { t: -178, w: 500 }, status: "stormy" }

Bez adaptera musielibyśmy w każdym komponencie sprawdzać, z którego API przyszły dane i odpowiednio je przetwarzać. To prowadzi do bałaganu!

Implementacja Adaptera w React

Stwórzmy adaptery, które ujednolicą dane z różnych API:

// Zunifikowany interfejs danych pogodowych
// { planet, temperature, windSpeed, condition }

function adaptMarsWeather(rawData) {
  return {
    planet: 'Mars',
    temperature: rawData.temp_celsius,
    windSpeed: rawData.wind_kph,
    condition: rawData.condition,
  };
}

function adaptJupiterWeather(rawData) {
  return {
    planet: 'Jupiter',
    temperature: rawData.temperature.value,
    windSpeed: rawData.windSpeed,
    condition: rawData.windSpeed > 300 ? 'extreme' : 'moderate',
  };
}

function adaptSaturnWeather(rawData) {
  return {
    planet: 'Saturn',
    temperature: rawData.readings.t,
    windSpeed: rawData.readings.w,
    condition: rawData.status,
  };
}

Teraz mamy trzy proste funkcje, z których każda przyjmuje surowe dane i zwraca obiekt o identycznej strukturze. Nasz komponent pogodowy może korzystać z tych danych bez wiedzy o tym, skąd pochodzą:

function PlanetWeatherCard({ weatherData }) {
  // weatherData ma ZAWSZE ten sam kształt dzięki adapterom
  return (
    <div className="weather-card">
      <h3>{weatherData.planet}</h3>
      <p>Temperatura: {weatherData.temperature} C</p>
      <p>Wiatr: {weatherData.windSpeed} km/h</p>
      <p>Stan: {weatherData.condition}</p>
    </div>
  );
}

Adapter jako Custom Hook

Adaptery doskonale sprawdzają się jako custom hooki, które opakowują zewnętrzne biblioteki:

// Adapter dla różnych bibliotek map kosmicznych
function useSpaceMap(provider) {
  const [map, setMap] = useState(null);

  useEffect(() => {
    let mapInstance;

    if (provider === 'galactic-maps') {
      // Biblioteka GalacticMaps ma swoje API
      mapInstance = new GalacticMaps.Chart('#map');
      mapInstance.init({ zoom: 5 });
    } else if (provider === 'star-atlas') {
      // StarAtlas ma zupełnie inne API
      mapInstance = StarAtlas.create(document.getElementById('map'), {
        level: 5,
        mode: '3d',
      });
    }

    // Zwracamy zunifikowany interfejs
    setMap({
      zoomIn: () => {
        if (provider === 'galactic-maps') mapInstance.setZoom(mapInstance.getZoom() + 1);
        else mapInstance.changeLevel(mapInstance.level + 1);
      },
      zoomOut: () => {
        if (provider === 'galactic-maps') mapInstance.setZoom(mapInstance.getZoom() - 1);
        else mapInstance.changeLevel(mapInstance.level - 1);
      },
      centerOn: (coords) => {
        if (provider === 'galactic-maps') mapInstance.panTo(coords);
        else mapInstance.focus({ x: coords.lat, y: coords.lng });
      },
    });

    return () => {
      if (provider === 'galactic-maps') mapInstance.destroy();
      else mapInstance.dispose();
    };
  }, [provider]);

  return map;
}

Dzięki temu hookowi, komponent korzystający z mapy nie musi wiedzieć, która biblioteka jest używana pod spodem. Gdybyśmy chcieli zmienić dostawcę map, wystarczy zmodyfikować tylko hook - żaden komponent się nie zmieni.

Wzorzec Facade

Czym jest Facade?

Wzorzec Facade (Fasada) dostarcza uproszczony interfejs do złożonego podsystemu. W React najczęściej implementujemy go jako hooki, które ukrywają skomplikowaną logikę za prostym API.

Pomyśl o panelu kontrolnym statku kosmicznego. Pilot nie musi znać szczegółów działania każdego systemu - naciska przycisk "Start silników" i cały złożony proces uruchamia się automatycznie. Fasada działa dokładnie tak samo.

Prosty przykład: Hook jako Facade

Bez fasady, komponent musi sam zarządzać wieloma szczegółami:

// BEZ Facade - komponent jest przytłoczony szczegółami
function MissionLauncher() {
  const [fuel, setFuel] = useState(0);
  const [systems, setSystems] = useState([]);
  const [crewReady, setCrewReady] = useState(false);
  const [countdown, setCountdown] = useState(null);
  const [launchStatus, setLaunchStatus] = useState('idle');
  const [errors, setErrors] = useState([]);

  // Sprawdzanie paliwa
  useEffect(() => {
    fetchFuelLevel().then(setFuel);
  }, []);

  // Sprawdzanie systemów
  useEffect(() => {
    checkAllSystems().then(setSystems);
  }, []);

  // Countdown
  useEffect(() => {
    if (countdown !== null && countdown > 0) {
      const timer = setTimeout(() => setCountdown(c => c - 1), 1000);
      return () => clearTimeout(timer);
    }
    if (countdown === 0) {
      executeLaunch().then(() => setLaunchStatus('launched'));
    }
  }, [countdown]);

  const startLaunch = async () => {
    if (fuel < 80) { setErrors(e => [...e, 'Za mało paliwa']); return; }
    if (!crewReady) { setErrors(e => [...e, 'Załoga niegotowa']); return; }
    const failedSystems = systems.filter(s => s.status !== 'ok');
    if (failedSystems.length > 0) {
      setErrors(e => [...e, 'Systemy niesprawne']);
      return;
    }
    setCountdown(10);
  };

  // ... reszta komponentu z ogromną ilością logiki
}

Z fasadą przenosimy całą tę logikę do hooka:

// Z Facade - hook ukrywa całą złożoność
function useMissionLaunch() {
  const [fuel, setFuel] = useState(0);
  const [systems, setSystems] = useState([]);
  const [crewReady, setCrewReady] = useState(false);
  const [countdown, setCountdown] = useState(null);
  const [status, setStatus] = useState('idle');
  const [errors, setErrors] = useState([]);

  useEffect(() => {
    fetchFuelLevel().then(setFuel);
    checkAllSystems().then(setSystems);
  }, []);

  useEffect(() => {
    if (countdown !== null && countdown > 0) {
      const timer = setTimeout(() => setCountdown(c => c - 1), 1000);
      return () => clearTimeout(timer);
    }
    if (countdown === 0) {
      executeLaunch().then(() => setStatus('launched'));
    }
  }, [countdown]);

  const launch = () => {
    const newErrors = [];
    if (fuel < 80) newErrors.push('Za mało paliwa');
    if (!crewReady) newErrors.push('Załoga niegotowa');
    const failedSystems = systems.filter(s => s.status !== 'ok');
    if (failedSystems.length > 0) newErrors.push('Systemy niesprawne');

    if (newErrors.length > 0) {
      setErrors(newErrors);
      return;
    }
    setCountdown(10);
    setStatus('countdown');
  };

  const abort = () => {
    setCountdown(null);
    setStatus('aborted');
  };

  return {
    // Proste, czytelne API
    launch,
    abort,
    status,
    countdown,
    errors,
    isReady: fuel >= 80 && crewReady && systems.every(s => s.status === 'ok'),
    fuelLevel: fuel,
    setCrewReady,
  };
}

// Komponent jest teraz czysty i prosty
function MissionLauncher() {
  const mission = useMissionLaunch();

  return (
    <div>
      <h1>Start misji</h1>
      <p>Paliwo: {mission.fuelLevel}%</p>
      <p>Status: {mission.status}</p>
      {mission.countdown !== null && <p>Odliczanie: {mission.countdown}</p>}
      {mission.errors.map((err, i) => <p key={i} style={{color: 'red'}}>{err}</p>)}
      <button onClick={mission.launch} disabled={!mission.isReady}>
        Start
      </button>
      <button onClick={mission.abort}>Przerwij</button>
    </div>
  );
}

Facade dla złożonych operacji

Facade jest szczególnie przydatny, gdy musisz skoordynować wiele operacji:

function useCrewManagement(missionId) {
  // Wewnętrznie zarządza wieloma źródłami danych
  const [crew, setCrew] = useState([]);
  const [assignments, setAssignments] = useState({});
  const [healthRecords, setHealthRecords] = useState({});

  useEffect(() => {
    Promise.all([
      fetchCrew(missionId),
      fetchAssignments(missionId),
      fetchHealthRecords(missionId),
    ]).then(([crewData, assignData, healthData]) => {
      setCrew(crewData);
      setAssignments(assignData);
      setHealthRecords(healthData);
    });
  }, [missionId]);

  // Prosty interfejs dla komponentu
  return {
    crewMembers: crew.map(member => ({
      ...member,
      role: assignments[member.id]?.role || 'Unassigned',
      healthStatus: healthRecords[member.id]?.status || 'Unknown',
    })),
    assignRole: (memberId, role) => {
      updateAssignment(missionId, memberId, role)
        .then(() => setAssignments(prev => ({
          ...prev,
          [memberId]: { ...prev[memberId], role },
        })));
    },
    isCrewReady: crew.length > 0 && crew.every(m =>
      assignments[m.id]?.role && healthRecords[m.id]?.status === 'fit'
    ),
  };
}

Kiedy stosować Adapter, a kiedy Facade?

CechaAdapterFacade
CelUjednolicenie niekompatybilnych interfejsówUproszczenie złożonego systemu
KiedyWiele źródeł danych o różnych formatachSkomplikowana logika do ukrycia
W ReactOpakowywanie zewnętrznych API/bibliotekCustom hooki ukrywające złożoność
Analogia kosmicznaTranslator języków obcych cywilizacjiPanel sterowania statku

Oba wzorce można łączyć - Facade może wewnętrznie korzystać z adapterów:

function useGalacticWeather(planets) {
  // Facade: upraszcza interfejs
  const [weather, setWeather] = useState({});

  useEffect(() => {
    const adapters = {
      mars: adaptMarsWeather,
      jupiter: adaptJupiterWeather,
      saturn: adaptSaturnWeather,
    };

    // Adapter: ujednolica dane z różnych API
    Promise.all(
      planets.map(planet =>
        fetchWeather(planet).then(raw => adapters[planet](raw))
      )
    ).then(results => {
      const weatherMap = {};
      results.forEach(w => { weatherMap[w.planet] = w; });
      setWeather(weatherMap);
    });
  }, [planets]);

  return {
    getWeather: (planet) => weather[planet] || null,
    isLoaded: Object.keys(weather).length === planets.length,
    coldestPlanet: Object.values(weather)
      .sort((a, b) => a.temperature - b.temperature)[0]?.planet || null,
  };
}

Podsumowanie

Wzorce Adapter i Facade to niezbędne narzędzia w arsenale kosmicznego programisty React:

  • Adapter pozwala ujednolicić niekompatybilne interfejsy, co jest kluczowe przy integracji z wieloma zewnętrznymi API i bibliotekami
  • Facade upraszcza złożone podsystemy, tworząc czytelne i łatwe w użyciu hooki
  • Oba wzorce zwiększają czytelność kodu, ułatwiają testowanie i redukują coupling między komponentami

Podobnie jak uniwersalny adapter zasilania pozwala podłączyć statek kosmiczny do dowolnej stacji dokującej w galaktyce, tak wzorce Adapter i Facade pozwalają naszym komponentom React współpracować z dowolnymi systemami bez zbędnych komplikacji.

Kod do tej lekcji: App.jsx
import React, { useState, useEffect } from 'react';

// ============================================
// WZORZEC ADAPTER I FACADE
// ============================================

// --- ADAPTER: Ujednolicanie danych z roznych API planet ---

// Symulacja surowych odpowiedzi z roznych API
const rawMarsData = { temp_celsius: -60, wind_kph: 25, condition: 'dusty' };
const rawJupiterData = { temperature: { value: -145, unit: 'C' }, windSpeed: 350 };
const rawSaturnData = { readings: { t: -178, w: 500 }, status: 'stormy' };

// Adaptery - kazdy zamienia surowe dane na wspolny format
function adaptMarsWeather(raw) {
  return {
    planet: 'Mars',
    temperature: raw.temp_celsius,
    windSpeed: raw.wind_kph,
    condition: raw.condition,
  };
}

function adaptJupiterWeather(raw) {
  return {
    planet: 'Jupiter',
    temperature: raw.temperature.value,
    windSpeed: raw.windSpeed,
    condition: raw.windSpeed > 300 ? 'extreme' : 'moderate',
  };
}

function adaptSaturnWeather(raw) {
  return {
    planet: 'Saturn',
    temperature: raw.readings.t,
    windSpeed: raw.readings.w,
    condition: raw.status,
  };
}

// Komponent korzystajacy z ujednoliconych danych
function PlanetWeatherCard({ weatherData }) {
  const getConditionColor = (condition) => {
    const colors = {
      dusty: '#ff9800', extreme: '#f44336',
      stormy: '#9c27b0', moderate: '#4caf50',
    };
    return colors[condition] || '#00d4ff';
  };

  return (
    <div style={cardStyle}>
      <h3 style={{ color: '#ffd700', marginBottom: '12px' }}>
        {weatherData.planet}
      </h3>
      <p>Temperatura: <strong>{weatherData.temperature} C</strong></p>
      <p>Wiatr: <strong>{weatherData.windSpeed} km/h</strong></p>
      <p>
        Stan:{' '}
        <span style={{ color: getConditionColor(weatherData.condition), fontWeight: 'bold' }}>
          {weatherData.condition}
        </span>
      </p>
    </div>
  );
}

// --- FACADE: Hook ukrywajacy zlozonosc ---

function useGalacticWeather() {
  const [weather, setWeather] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedPlanet, setSelectedPlanet] = useState(null);

  useEffect(() => {
    // Facade ukrywa cala logike pobierania i adaptowania danych
    const timer = setTimeout(() => {
      const adapted = [
        adaptMarsWeather(rawMarsData),
        adaptJupiterWeather(rawJupiterData),
        adaptSaturnWeather(rawSaturnData),
      ];
      setWeather(adapted);
      setLoading(false);
    }, 800);
    return () => clearTimeout(timer);
  }, []);

  // Prosty interfejs dla komponentu
  return {
    weather,
    loading,
    selectedPlanet: selectedPlanet
      ? weather.find(w => w.planet === selectedPlanet)
      : null,
    selectPlanet: setSelectedPlanet,
    coldestPlanet: weather.length > 0
      ? weather.reduce((a, b) => a.temperature < b.temperature ? a : b).planet
      : null,
    averageTemp: weather.length > 0
      ? Math.round(weather.reduce((sum, w) => sum + w.temperature, 0) / weather.length)
      : 0,
  };
}

// --- Glowna aplikacja ---
function App() {
  const {
    weather, loading, selectedPlanet,
    selectPlanet, coldestPlanet, averageTemp,
  } = useGalacticWeather();

  return (
    <div style={appStyle}>
      <h1 style={{ color: '#00d4ff', textAlign: 'center', marginBottom: '8px' }}>
        Adapter i Facade - Pogoda w galaktyce
      </h1>
      <p style={{ textAlign: 'center', color: '#aaa', marginBottom: '24px' }}>
        Dane z 3 roznych API, ujednolicone przez Adaptery, uproszczone przez Facade
      </p>

      {loading ? (
        <p style={{ textAlign: 'center', color: '#ffd700' }}>Laczenie z sondami...</p>
      ) : (
        <>
          <div style={statsStyle}>
            <span>Najzimniejsza: <strong style={{ color: '#00d4ff' }}>{coldestPlanet}</strong></span>
            <span>Srednia temp: <strong style={{ color: '#ff9800' }}>{averageTemp} C</strong></span>
          </div>

          <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap', justifyContent: 'center' }}>
            {weather.map(w => (
              <div
                key={w.planet}
                onClick={() => selectPlanet(w.planet)}
                style={{ cursor: 'pointer', flex: '1', minWidth: '200px' }}
              >
                <PlanetWeatherCard weatherData={w} />
              </div>
            ))}
          </div>

          {selectedPlanet && (
            <div style={{ ...cardStyle, marginTop: '20px', borderColor: '#ffd700' }}>
              <h3 style={{ color: '#ffd700' }}>Szczegoly: {selectedPlanet.planet}</h3>
              <p>Temperatura: {selectedPlanet.temperature} C</p>
              <p>Wiatr: {selectedPlanet.windSpeed} km/h</p>
              <p>Warunki: {selectedPlanet.condition}</p>
              <button
                onClick={() => selectPlanet(null)}
                style={btnStyle}
              >
                Zamknij
              </button>
            </div>
          )}

          {/* TODO: Dodaj nowa planete (np. Neptun) z wlasnym surowym formatem danych
              i napisz dla niej adapter. Surowy format Neptuna:
              { metrics: { tempC: -214, windMs: 580 }, weather: 'icy' }
              Adapter powinien zamienic windMs na km/h (x 3.6) */}
        </>
      )}
    </div>
  );
}

const appStyle = {
  background: '#0d1b2a', minHeight: '100vh', padding: '20px',
  fontFamily: 'Arial, sans-serif', color: '#e0e1dd',
};
const cardStyle = {
  background: '#1b2838', borderRadius: '12px', padding: '20px',
  border: '1px solid #2a3f5f',
};
const statsStyle = {
  display: 'flex', justifyContent: 'center', gap: '30px',
  marginBottom: '20px', padding: '12px',
  background: '#1b2838', borderRadius: '8px',
};
const btnStyle = {
  marginTop: '10px', padding: '8px 20px', background: '#ff9800',
  color: '#000', border: 'none', borderRadius: '6px',
  cursor: 'pointer', fontWeight: 'bold',
};

export default App;

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Zadania praktyczne w grze

  • Układanie w poziomie

    Ułóż poprawną składnię lazy loading komponentu:

  1. Ułóż w kolejnościSkładnia React.lazy z Suspense

Przydatne artykuły