For most countries, transiting doesn't count as "being there" for Germany. However, the UK is an area of variant of concern, so it looks as though the quarantine requirements still apply to transit passengers:
https://www.auswaertiges-amt.de/en/e...eUndAufenthalt
So assuming that entry to Germany on your passport is permitted, I think you'd be allowed in with a negative test, but have to quarantine for 14 days if coming via London. There's no early test-to-release option for people coming from variant of concern areas. Some more info on the German UK embassy page:
https://uk.diplo.de/uk-en/02/coronavirus
Edit: Your plan to go to MAD via LHR then on to BER wouldn't exempt you from quarantine either, unless you were spending ten days in Spain before onward travel to Germany. In practice though, I'm not sure how that would work as I don't think you need to complete a passenger locator form when travelling from Spain to Germany. But if you want to be completely sure you'd need to transit via a non-variant-list country.