The concept itself is described in the last link in my signature.
The reason for all the ''' is simple:
If you want to get the dynamic sql to look like "...CASE factory WHEN 'F1' ..." you have to provide the quotation marks around F1, since those are not part of the value stored in your table.
If you want to have a single quotation mark in your dynamic statement you need to surround it by separate quotation marks.
It's basically the same concept as if you'd like to use the value O'Connor in an select statement:
SELECT 'O'Connor' (invalid) vs.
SELECT 'O''Connor' (valid) vs.
SELECT 'O''Connor'+'''' (valid)