Why were medieval castles built a certain design?

Medieval castles were built the way they were because that was an effective means of defencing the community from invaders.